将OGR图层与Python中的属性表合并

问题描述 投票:0回答:1

这是来自Python GDAL / OGR食谱的Python中的OGR图层合并示例。https://pcjericks.github.io/py-gdalogr-cookbook/vector_layers.html#merge-ogr-layers

import os, ogr, osr

outputMergefn = 'merge.shp'
directory = "/Users/UserName/Downloads/"
fileStartsWith = 'test'
fileEndsWith = '.shp'
driverName = 'ESRI Shapefile'
geometryType = ogr.wkbPolygon

out_driver = ogr.GetDriverByName( driverName )
if os.path.exists(outputMergefn):
   out_driver.DeleteDataSource(outputMergefn)
out_ds = out_driver.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)
        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_feat = None
           out_layer.SyncToDisk()

不过,此示例未合并属性表。有没有一种方法可以在Python中使用OGR?

python gis ogr
1个回答
0
投票

它复制目标shapefile中存在的字段的属性。

def merge(target, source):
    #layer of target shp
    driver = ogr.GetDriverByName("ESRI Shapefile")
    ds_t = driver.Open(target, 1)
    tr_layer = ds_t.GetLayer()

    # layer of soruce shp
    driver = ogr.GetDriverByName("ESRI Shapefile")
    ds_s = driver.Open(source, 0)
    sr_layer = ds_s.GetLayer()

    #copy features:
    for f in sr_layer:
        defn=tr_layer.GetLayerDefn()
        out_feat = ogr.Feature(defn)

        for i in range(0, defn.GetFieldCount()):
            out_feat.SetField(defn.GetFieldDefn(i).GetNameRef(),f.GetField(i))

        out_feat.SetGeometry(f.GetGeometryRef().Clone())
        tr_layer.CreateFeature(out_feat)
        out_feat=None  
© www.soinside.com 2019 - 2024. All rights reserved.