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'

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(),
feature = in_layer.GetFeature(1)
[dest_layer.CreateField(feature.GetFieldDefnRef(i)) for i in range(feature.GetFieldCount())]
for feature in master_feature_list:
    feature_new = ogr.Feature(in_layer.GetLayerDefn())
        feature_new.SetField('trafficability', trafficability_dict[feature.GetField('osm_id')])
        feature_new.SetField('trafficability', -1)
    print feature.DumpReadable()
    assert(0 == dest_layer.CreateFeature(feature_new))
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.

  • This looks like it could be caused by one of the common GDAL Gotchas: A dataset needs to be closed / go out of Python scope to be written to disk. Try appending data_out = None to your script or maybe give Fiona a try - which makes handling OGR data a lot more pythonic than the standard wrappers.
    – Kersten
    Jun 21, 2016 at 19:34
  • 1
    If you are running your script from an IDE like pyscripter, you'll run into these sort of issues as the IDE can hold objects open in memory after the script completes. This can be good when you're debugging, but not so good when you're running your script.
    – user2856
    Jun 27, 2016 at 1:06

1 Answer 1


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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.