datasource层次的拷贝
  1. from osgeo import ogr
  2. import os,math
  3. inshp = "C:\tmp\test.shp"
  4. ds = ogr.Open(inshp)
  5. driver = ogr.GetDriverByName("ESRI Shapefile")
  6. outputfile = 'C:\tmp\test_copy.shp'
  7. if os.access( outputfile, os.F_OK) : #已经有该文件
  8. driver.DeleteDataSource(outputfile) #删除
  9. pt_cp = driver.CopyDataSource(ds, outputfile) #根据数据源ds创建数据,返回指针
  10. pt_cp.Release() #释放指针,将数据写入到磁盘

layer层次的拷贝
  1. from osgeo import ogr
  2. import os,math
  3. inshp = "C:\tmp\test.shp"
  4. ds = ogr.Open(inshp)
  5. driver = ogr.GetDriverByName("ESRI Shapefile")
  6. outputfile = "C:\tmp\test_copy2.shp"
  7. if os.access( outputfile, os.F_OK):
  8. driver.DeleteDataSourse( outputfile )
  9. layer = ds.GetLayer()
  10. newds = driver.CreateDataSource(outputfile) #首先得有数据源
  11. pt_layer = newds.CopyLayer(layer, 'abcd') #复制图层,返回指针
  12. newds.Destroy() #对newds进行Destroy()操作,才能将数据写入磁盘

feature层次的拷贝
  1. from osgeo import ogr
  2. import os,math
  3. inshp = 'C:\tmp\test.shp'
  4. ds = ogr.Open(inshp)
  5. driver = ogr.GetDriverByName("ESRI Shapefile")
  6. outputfile = 'c:\tmp\test.shp'
  7. if os.access( outputfile, os.F_OK ):
  8. driver.DeleteDataSource( outputfile )
  9. newds = driver.CreateDataSource(outputfile) #按outputfile的数据源创建一个newds
  10. layernew = newds.CreateLayer('worldcopy',None,ogr.wkbLineString) #创建一个图层
  11. layer = ds.GetLayer() #得到原数据源的图层
  12. extent = layer.GetExtent() #图层范围
  13. # 遍历旧图层的所有feature,进行复制
  14. feature = layer.GetNextFeature()
  15. while feature is not None:
  16. layernew.CreateFeature(feature)
  17. feature = layer.GetNextFeature()
  18. newds.Destroy() # 包括了将数据flush到磁盘