You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python创建TIFF文件时遇NoneType错误求助

GDAL创建TIFF时出现NoneType错误排查

我编写了如下Python代码:

county = '003-alpine'
candidate = 'trump'

out_tiff = '/Users/deas/Documents/Python/precinct-master/data/tif/' + candidate + '/' + county + '.tif'

target_ds = gdal.GetDriverByName('Gtiff').Create(out_tiff, cols, rows, 1, gdal.GDT_Byte)
target_ds.SetGeoTransform((x_min, pixel_width, 0, y_max, 0, -pixel_height))
band = target_ds.GetRasterBand(1)
no_data_value = 255
band.SetNoDataValue(no_data_value)
band.FlushCache()

gdal.RasterizeLayer(target_ds, [1], source_layer, options=["ATTRIBUTE=isHill"])
target_ds_srs = osr.SpatialReference()
target_ds_srs.ImportFromEPSG(4326)
target_ds.SetProjection(target_ds_srs.ExportToWkt())

source_ds = None

source_ds = gdal.OpenEx(shp, gdal.OF_VECTOR | gdal.OF_UPDATE)
source_ds.ExecuteSQL("ALTER TABLE "+county+" DROP COLUMN isHill")

source_ds = None

运行时出现错误:

AttributeError: 'NoneType' object has no attribute 'SetGeoTransform'

我是GDAL新手,所有文件夹已正确创建并放置,请问问题出在哪里?


问题原因分析

这个错误直接说明target_ds是None,也就是gdal.GetDriverByName('Gtiff').Create()方法调用失败,没有成功创建TIFF数据集。常见失败原因有以下几种:

  • 路径问题:MacOS路径区分大小写,检查out_tiff拼写是否准确,比如'Gtiff'和'GTiff'是不同的;另外路径中的空格、特殊字符也可能导致创建失败。
  • 无效行列数:cols和rows必须是正整数,如果这两个值为0、负数或未正确赋值(比如从源数据获取时出错),Create方法会返回None。
  • 驱动缺失:如果gdal.GetDriverByName('Gtiff')返回None,说明GDAL安装不完整,缺少GTiff驱动。
  • 权限不足:目标路径没有写入权限,比如文件夹设为只读,或当前用户无创建文件的权限。

排查与解决步骤

  1. 验证路径有效性:打印out_tiff的具体值,手动导航到该路径并尝试创建空文件,确认路径可达且有写入权限。
  2. 检查行列数参数:在Create调用前打印cols和rows的值,确保是大于0的整数:
    print(f"cols: {cols}, rows: {rows}")
    
  3. 检查GTiff驱动:单独获取驱动并验证(注意GDAL驱动名通常是GTiff而非Gtiff):
    driver = gdal.GetDriverByName('GTiff')
    if driver is None:
        print("GTiff驱动未找到,请检查GDAL安装")
        exit()
    
  4. 获取详细错误日志:在Create调用后立即检查结果,打印GDAL的错误信息是最直接的排查方式:
    target_ds = driver.Create(out_tiff, cols, rows, 1, gdal.GDT_Byte)
    if target_ds is None:
        print(f"创建TIFF失败:{gdal.GetLastErrorMsg()}")
        exit()
    

内容的提问来源于stack exchange,提问作者The Mad Scientist

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 21:17:29