CentOS 7下Python GDAL处理GRIB2文件报错的解决方法
GRIB2转GeoTIFF时GDAL报错的解决方法
问题场景
尝试使用Python GDAL将GRIB2文件转换为GeoTIFF,代码如下:
import gdal import osr ds = gdal.Open(r"/home/test/gfs.t12z.sfluxgrbf000.grib2",1) gph = ds.GetRasterBand(84).ReadAsArray() press = ds.GetRasterBand(54).ReadAsArray() / 100 temp = ds.GetRasterBand(52).ReadAsArray() u = ds.GetRasterBand(50).ReadAsArray() v = ds.GetRasterBand(51).ReadAsArray() corr_press = press * (1 - (0.0065*gph/(0.0065*gph + temp + 273.15)))**-5.257 driver = gdal.GetDriverByName('GTiff') outRaster = driver.Create("/home/test/vardah2.tiff", ds.RasterXSize, ds.RasterYSize, 4, gdal.GDT_Float32) outRaster.SetGeoTransform(ds.GetGeoTransform()) outband = outRaster.GetRasterBand(1) outband.WriteArray(corr_press) outband.SetMetadata({'name': 'press'}) outRasterSRS = osr.SpatialReference() outRasterSRS.ImportFromEPSG(4326) outRaster.SetProjection(outRasterSRS.ExportToWkt()) outband.FlushCache()
在CentOS 7运行时出现错误:
ERROR 6: The GRIB driver does not support update access to existing datasets. Traceback (most recent call last): File "ficky.py", line 4, in <module> gph = ds.GetRasterBand(84).ReadAsArray() AttributeError: 'NoneType' object has no attribute 'GetRasterBand'
解决方案
1. 修正文件打开模式
报错核心原因:gdal.Open()的第二个参数1代表更新模式,但GRIB驱动不支持写入/更新操作,导致返回None,触发后续AttributeError。
将打开方式改为只读模式(默认模式,参数可省略):
# 两种写法等价,均为只读打开 ds = gdal.Open(r"/home/test/gfs.t12z.sfluxgrbf000.grib2") # 或显式指定只读模式 ds = gdal.Open(r"/home/test/gfs.t12z.sfluxgrbf000.grib2", 0)
2. 验证波段索引正确性
代码中使用的波段号(84、54、52等)必须匹配目标GRIB2文件的实际波段。用GDAL命令行工具查看文件波段详情:
gdalinfo /home/test/gfs.t12z.sfluxgrbf000.grib2
输出会列出所有波段的序号、变量描述等信息,确认需要的变量对应的波段号是否正确。
3. 确保CentOS 7的GDAL支持GRIB2驱动
CentOS 7默认源的GDAL可能未编译GRIB2支持,需安装带GRIB2驱动的版本:
- 通过EPEL源安装:
sudo yum install epel-release sudo yum install gdal gdal-python - 源码编译(若EPEL版本不支持):
需先安装依赖库eccodes(GRIB2解析库),再编译GDAL:# 安装编译依赖 sudo yum install gcc gcc-c++ make cmake libcurl-devel libpng-devel libjpeg-devel libtiff-devel # 安装eccodes sudo yum install eccodes-devel # 下载并编译GDAL wget https://download.osgeo.org/gdal/3.6.4/gdal-3.6.4.tar.gz tar xzf gdal-3.6.4.tar.gz cd gdal-3.6.4 ./configure --with-eccodes make -j$(nproc) sudo make install sudo ldconfig
4. 添加错误检查逻辑
在代码中增加文件打开的判断,提前拦截错误:
ds = gdal.Open(r"/home/test/gfs.t12z.sfluxgrbf000.grib2") if ds is None: print("无法打开GRIB2文件,请检查文件路径或GDAL驱动支持") exit(1)
内容的提问来源于stack exchange,提问作者jms1980
相关产品推荐
相关产品推荐

