# 设置driver
driver = ogr.GetDriverByName('ESRI Shapefile')
# 打开输入的矢量
inDs = driver.Open(r'E:/wang2/python/polygon_jingweidu.shp', 0)
if inDs is None:
print("Could not open", 'sites.shp')
sys.exit(1)
# 打开输入矢量的图册
inLayer = inDs.GetLayer()
srs = inLayer.GetSpatialRef()
outshp = r'E:/wang2/python/polygon1.shp'
# 检查所需创建的矢量是否已存在
if os.path.exists(outshp):
driver.DeleteDataSource(outshp)
# 创建矢量
outDs = driver.CreateDataSource(outshp)
if outDs is None:
print("Could not create file")
sys.exit(1)
# 创建图册
outLayer = outDs.CreateLayer('test', geom_type=ogr.wkbPolygon)
# 将输入矢量的属性应用到新矢量
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()