我想从一个文件夹中读取许多 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' object has no attribute 'write'
干杯!