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')
完结!