Python 用ogr实现把一个矢量图层的属性字段赋给新创建的图层
时间: 2024-06-08 19:00:49 浏览: 130
使用 ogr 可以很方便地实现将一个矢量图层的属性字段赋给新创建的图层。
以下是一个示例代码,假设我们有一个名为“old_layer.shp”的矢量图层,现在要创建一个名为“new_layer.shp”的图层,并将“old_layer.shp”的属性字段赋值给“new_layer.shp”:
```python
from osgeo import ogr
# 打开旧图层
old_ds = ogr.Open('old_layer.shp', 0)
old_layer = old_ds.GetLayer()
# 创建新图层
new_ds = ogr.GetDriverByName('ESRI Shapefile').CreateDataSource('new_layer.shp')
new_layer = new_ds.CreateLayer('new_layer', geom_type=ogr.wkbPolygon)
# 将旧图层的属性表结构复制到新图层
new_layer_def = old_layer.GetLayerDefn()
for i in range(new_layer_def.GetFieldCount()):
field_def = new_layer_def.GetFieldDefn(i)
new_layer.CreateField(field_def)
# 将旧图层的属性值复制到新图层
new_layer.StartTransaction()
for old_feature in old_layer:
new_feature = ogr.Feature(new_layer_def)
for i in range(new_layer_def.GetFieldCount()):
field_def = new_layer_def.GetFieldDefn(i)
field_value = old_feature.GetField(field_def.name)
new_feature.SetField(field_def.name, field_value)
new_geometry = old_feature.GetGeometryRef().Clone()
new_feature.SetGeometry(new_geometry)
new_layer.CreateFeature(new_feature)
new_feature = None
new_layer.CommitTransaction()
# 清理
old_layer = None
old_ds = None
new_layer = None
new_ds = None
```
在这个示例代码中,我们首先打开旧图层“old_layer.shp”,然后创建新图层“new_layer.shp”。接着,我们将旧图层的属性表结构复制到新图层,并将旧图层的属性值复制到新图层。最后,我们清理并关闭数据源和图层。
注意,如果要将某个属性字段的值进行操作并赋值给新图层的属性字段,可以在复制属性值的过程中进行处理。
阅读全文