【问题标题】:Convert grib files to text files with Python使用 Python 将 grib 文件转换为文本文件
【发布时间】:2018-02-07 00:03:19
【问题描述】:

我想从一个文件夹中读取许多 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' 对象没有属性 'write'

干杯!

【问题讨论】:

    标签: python grib


    【解决方案1】:

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

    def process_message(grb, outfile):
        with open(outfile, 'w') as output:
            ...
    

    【讨论】:

    • 现在,当我运行代码时,没有错误,但没有任何反应......没有创建文本文件......
    猜你喜欢
    • 2013-06-28
    • 2019-03-14
    • 1970-01-01
    • 2021-12-18
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多