python在windows和linux系统下批量读取grib2数据

python在windows系统和linux系统读取grib或者grib2数据所用的库不一样,下面分别细说。

1.python在linux系统下批量读取grib或grib2数据

   linux系统对python读取grib数据很友好,有很多库可以读取,这里我们采用eccodes读取

  首先,需要清楚要提取的变量名或者编号

  ##以变量名提取数据

 #以变量编号提取数据

from reki.format.grib.eccodes import load_message_from_file
import eccodes
cr = load_message_from_file(file_path + '/' + file, parameter={
    "discipline": 0,
    "parameterCategory": 16,
    "parameterNumber": 224
},
                            level_type="surface",
                            level=0,
                            )

values = eccodes.codes_get_double_array(cr, "values")
values = values.reshape([501,751])
values = values[::-1]

2. python在windows系统下批量读取grib或grib2数据

   试验了很多方法,最终发现还是得借助于wgrib.exe程序,需要的可以私信我

  首先,我们用wgrib程序查看下grib数据

os.chdir(r"\wgrib2")
os.system(r"wgrib2 mef.gra.000.2022041100001.grb2 -v")

 如图,我们提取行号为14的变量,将其输出到文件里

os.system(r"wgrib2 mef.gra.000.2022041100001.grb2 -d 14 -text 2022041100001.txt")

 但是,这样的数据是一行一个数值的输出,我们需要把它转换为数组输出到文件里,且需要批量运行。采取方式如下

aa = wgrib_name + ' ' + file_in_name + ' -d 14 -text ' + file_out_temp_name
os.system(aa)

将原temp文件中的数值读入,转换为数组再输出到新文件里

with open(file_out_temp_name,'r') as file1:
    lines = file1.readlines()
    for line in lines[1:]:    #首行为经纬度范围,去掉首行
        data_new.append(line.strip("\n"))    #去掉换行符
    data_arr = np.array(data_new).reshape(ynum,xnum)

with open(file_out_name,'w') as file2:
    for j in range(0,ynum):
        for i in range(0,xnum):
            file2.write(("%8.2f")%(float(data_arr[j,i])))
        file2.write('\n')

完结!

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值