【问题标题】:Methods of Merging layers/shapefiles using OGR in python在 python 中使用 OGR 合并图层/形状文件的方法
【发布时间】:2016-04-17 04:41:47
【问题描述】:

我是 python 新手,正在尝试更轻松地使用 python 自动化 GIS 任务。任何帮助表示赞赏

我有两个包含点的层,我试图在 python 中使用 Ogr 将它们合并为一个层。以下是我在网站上找到的代码,但它给了我一个错误

AttributeError: 'NoneType' 对象没有属性 'GetLayer'

我认为导致此错误的行是:

ds = ogr.Open(目录+文件)

我想知道为什么在这一步没有生成任何东西,我也想知道是否有不同/更好的方法来使用 gdal/ogr python 合并图层

outputMergefn = 'Merge.shp'
directory = "C:/Users/Robin/Documents/Python Final Project/Final_Project/Output"
filestartswith = 'C'
FileEndsWith = '.shp'
drivername = 'ESRI Shapefile'
geometrytype = ogr.wkbMultiPoint
ptdriver = ogr.GetDriverByName('ESRI Shapefile')

if os.path.exists(outputMergefn):
    ptdriver.DeleteDataSource(outputMergefn)
out_ds = ptdriver.CreateDataSource(outputMergefn)
out_layer = out_ds.CreateLayer(outputMergefn, geom_type = geometrytype)

filelist = os.listdir(directory)
for file in filelist:
    if file.startswith(filestartswith) and file.endswith(FileEndsWith):
        print file
        ds = ogr.Open(directory + file)
        if ds is None:
            print "This is None"
        lyr = ds.GetLayer()
        for feat in lyr:
            out_feat = ogr.Feature(out_layer.GetLayerDefn())
            out_feat.SetGeometry(feat.GetGeometryRef().Clone())
            out_layer.CreateFeature(out_feat)
            out_layer.SyncToDisk()

【问题讨论】:

  • None 在出现错误时返回。将ogr.UseExceptions() 放在顶部附近以查看错误是什么。可能是找不到数据集。此外,使用 OGR,您可以将 shapefile 目录作为单个数据集打开,每个 shapefile 具有多个层。
  • 谢谢Mike,你是对的,我没有在上面定义的目录中的Output之后添加“/”。现在运行良好。
  • 你能发布最终代码并关闭问题吗?我还想使用 OGR 合并 shapefile,看看解决方案会很有用。

标签: python merge layer gdal ogr


【解决方案1】:

目录有问题。在您指定的目录中,不存在 shapefile。这就是GetLayer() 函数出错的原因。因为根据目录,数据源应该是shapefile,但是由于目录错误,数据源不是shapefile(可能是文件夹或其他文件)。而当数据源不是shapefile时,则无法使用GetLayer()函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-16
    • 1970-01-01
    • 2019-09-01
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多