I am trying to write a simple list of features and export it as a KML file, adding one extra attribute: in this case trafficability. However, ogr is failing to flush the data to disk when I run the script. Instead, the XML is clearly cut off mid-element. I have even tried explicitly calling SyncToDisk, but it has still failed to write the element. Are there any other calls I need to make to ensure that the full file is indeed written to the disk?
driver = ogr.GetDriverByName('KML')
output_file = 'traffic.kml'
driver.DeleteDataSource(output_file)
data_out = driver.CreateDataSource(output_file)
fldDef = ogr.FieldDefn("trafficability", ogr.OFTReal)
data_in = ogr.Open(osm_file)
in_layer = data_in.GetLayer(1)
srs = osr.SpatialReference()
dest_layer = data_out.CreateLayer('layer1',
srs = in_layer.GetSpatialRef(),
geom_type=in_layer.GetLayerDefn().GetGeomType())
feature = in_layer.GetFeature(1)
[dest_layer.CreateField(feature.GetFieldDefnRef(i)) for i in range(feature.GetFieldCount())]
dest_layer.CreateField(fldDef)
for feature in master_feature_list:
feature_new = ogr.Feature(in_layer.GetLayerDefn())
feature_new.SetFrom(feature)
try:
feature_new.SetField('trafficability', trafficability_dict[feature.GetField('osm_id')])
except:
feature_new.SetField('trafficability', -1)
print feature.DumpReadable()
assert(0 == dest_layer.CreateFeature(feature_new))
dest_layer.SyncToDisk()
data_out.SyncToDisk()
print("Syncing to to disk", data_out.SyncToDisk())
print('Done conversion!')
This is probably a really silly bug, but the documentation on OGR can be lacking at times.
Answer
This is one of the most common GDAL/OGR Python Gotchas: A dataset is only written to disk after it is closed.
Closing a dataset happens when it goes out of scope. This can be done in a number of ways and one of the following needs to be appended to the end of your script.
data_out = None
data_out = "some new value"
del(data_out)
There are libraries that make the usage of GDAL from Python more pythonic by mitigating a lot of these gotchas, implementing new file handling methods, etc. The most popular are rasterio and fiona.
No comments:
Post a Comment