我正在尝试使用gdal / ogr读取geojson文件,并创建另一个具有相同功能并选择其原始字段的geojson文件。可行!
您可以在此处下载文件: https://catalog.data.gov/dataset/building-footprint-gis-data/resource/1d33da3b-3e64-4551-9188-f572aa535874
如果在创建新文件时尝试更改字段名称,则会出现问题。如果我打开新文件的属性表,则为空。新名称已创建,但表中没有存储任何值。
我尝试了相同的代码读取shapefile和gml文件,并且可以工作。这意味着我已经能够使用新的文件名及其原始值创建一个新文件。
仅当要读取的文件是geojson时,并且仅当我尝试更改字段名称时,才会出现问题。我注意到任何geojson文件都在发生这种情况,不仅是我在此脚本中使用的那个。
from osgeo import ogr,osr
input = r"E:\PARSING_OGR\DATA\LESSONS\BloomingtonBuildings.geojson"
output = r"E:\PARSING_OGR\RESULTS\LESSONS\FILES\BloomingtonBuildings.geojson"
spatialRefSource = osr.SpatialReference()
spatialRefSource.ImportFromEPSG(2966)
driver = ogr.GetDriverByName('GeoJSON')
dataSource = driver.Open(input)
layer = dataSource.GetLayer()
newDataSource = driver.CreateDataSource(output)
newLayer = newDataSource.CreateLayer('BloomingtonBuildings',srs = spatialRefSource,geom_type=ogr.wkbPolygon)
layerDefinition = layer.GetLayerDefn()
fieldDefn1 = layerDefinition.GetFieldDefn(0)
fieldDefn2 = layerDefinition.GetFieldDefn(1)
fieldDefn3 = layerDefinition.GetFieldDefn(3)
fieldDefn4 = layerDefinition.GetFieldDefn(8)
fieldDefn1.SetName('FIELD1')
fieldDefn2.SetName('FIELD2')
fieldDefn3.SetName('FIELD3')
fieldDefn4.SetName('FIELD4')
newLayer.CreateField(fieldDefn1)
newLayer.CreateField(fieldDefn2)
newLayer.CreateField(fieldDefn3)
newLayer.CreateField(fieldDefn4)
newFeatureDefn = newLayer.GetLayerDefn()
for feature in layer:
newFeature = ogr.Feature(newFeatureDefn)
newFeature.SetGeometry(feature.GetGeometryRef())
newFeature.SetField('FIELD1', feature.GetField('FIELD1'))
newFeature.SetField('FIELD2', feature.GetField('FIELD2'))
newFeature.SetField('FIELD3', feature.GetField('FIELD3'))
newFeature.SetField('FIELD4', feature.GetField('FIELD4'))
newLayer.CreateFeature(newFeature)
feature= None
newFeature= None
dataSource= None
newDataSource= None
如果有人可以帮助我解决此问题,我将不胜感激。