Python+GDAL | 根据已有矢量创建新的矢量

这篇文章主要描述了如何使用GDAL/OGR创建矢量文件。

代码

import ogr,sys,os

os.chdir(r'E:\')

#设置driver
driver = ogr.GetDriverByName('ESRI Shapefile')
#打开输入的矢量
inDs = driver.Open('sites.shp', 0)
if inDs is None:
    print("Could not open", 'sites.shp')
    sys.exit(1)
#打开输入矢量的图册
inLayer = inDs.GetLayer()

#检查所需创建的矢量是否已存在
if os.path.exists('test.shp'):
    driver.DeleteDataSource('test.shp')
#创建矢量
outDs = driver.CreateDataSource('test.shp')
if outDs is None:
    print("Could not create file")
    sys.exit(1)
#创建图册
outLayer = outDs.CreateLayer('test', geom_type=ogr.wkbPoint)

#将输入矢量的属性应用到新矢量
fieldDefn = inLayer.GetFeature(0).GetFieldDefnRef('id')
outLayer.CreateField(fieldDefn)
featureDefn = outLayer.GetLayerDefn()

cnt = 0
inFeature = inLayer.GetNextFeature()
while inFeature:
    outFeature = ogr.Feature(featureDefn)
    outFeature.SetGeometry(inFeature.GetGeometryRef())
    outLayer.CreateFeature(outFeature)
    inFeature.Destroy()
    outFeature.Destroy()
    
    cnt = cnt+1
    if cnt < 10: inFeature = inLayer.GetNextFeature()
    else: break

inDs.Destroy()
outDs.Destroy()
上一篇:SHP 文件坐标转换成GCJ02


下一篇:Egret的容器--删除对象,遮罩