I want to read many grib files from a folder, and then save as text files. The name of the text file will be same name as grib file. My code:
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()
When I run the code, I get this error: AttributeError: 'str' object has no attribute 'write'
Cheers !
outfile
is a string not a file, glob returns a list of filepaths. You need to open it inprocess_message
.