使用Python将grib文件转换为文本文件

时间:2017-08-29 13:38:01

标签: python grib

我想从文件夹中读取许多grib文件,然后另存为文本文件。 文本文件的名称与grib文件的名称相同。 我的代码:

import pygrib, os, glob

LAT1 = None
LAT2 = None
LON1 = None
LON2 = None

def process_message(grb, outfile):
    tmps = "%s" % grb
    wtitle = tmps.split(':')[1]
    wtime = tmps.split(':')[len(tmps.split(':'))-1].split(' ')[1]
    data, lat, lons = grb.data(LAT1, LAT2, LON1, LON2)
    for i in xrange(len(data)):
        tdata = data[i]
        tlat = lat[i]
        tlon = lons[1]
    for j in xrange(len(tdata)):
        wdata = tdata[j]
        wlat = tlat[j]
        wlon = tlon[j]
        outfile.write("%s, %s, %s, %s, %s\n" % (wtitle, wtime, wlat, 
   wlon, wdata)) 

os.chdir('/home/george/mona_modificat/data')        
filenames = glob.glob('*.grb')

for f in filenames:
        grbs = pygrib.open(f)
        grbs.seek(0)
        outfile = f
        for grb in grbs:
            process_message(grb, outfile)
            os.rename(outfile, outfile + '.txt')
        grbs.close()

当我运行代码时,我收到此错误: AttributeError:' str'对象没有属性'写'

干杯!

1 个答案:

答案 0 :(得分:1)

outfile是一个字符串而不是一个文件,glob返回一个文件路径列表。您需要在process_message中打开它。

def process_message(grb, outfile):
    with open(outfile, 'w') as output:
        ...
相关问题