My goal is to iterate over features in a given KML file and save each feature as a seperate KML file. I'm using python and it seems that ogr module can do it but I can't figure out how. I am able to read a KML file into <class 'osgeo.ogr.DataSource'> and <class 'osgeo.ogr.Layer'> simply using:

import ogr

fn = r'C:\Users\kml folder\terre.kml'
driver = ogr.GetDriverByName('KML')
dataSource = driver.Open(fn, 0)
layer = dataSource.GetLayer()

I am also able to iterate over the features in the layer but from here on I can't seem to find the right way to save each feature as a separate KML.

  • Create a template KML with placeholders for substitution with placemarks you select from the source KML.
    – swatchai
    Commented Feb 13, 2018 at 5:52
  • Can you give me an example on how to do so?
    – user88484
    Commented Feb 13, 2018 at 7:12

2 Answers 2


Try the following script:

from osgeo import ogr

fn = r'C:\Users\kml folder\terre.kml'
driver = ogr.GetDriverByName('KML')
dataSource = driver.Open(fn)
layer = dataSource.GetLayer()
sr = layer.GetSpatialRef()  # Spatial Reference

dst = r""  # Output directory
new_feat = ogr.Feature(layer.GetLayerDefn())  # Dummy feature

for id, feat in enumerate(layer):
    new_ds = driver.CreateDataSource(r"{}\feat_{}.kml".format(dst, id))
    new_lyr = new_ds.CreateLayer('feat_{}'.format(id), sr, ogr.wkbPolygon)  # You have to specify the geometry type the layer will contain here with an ogr constant. I assume it is polygon but it can be changed.
    geom = feat.geometry().Clone()

    del new_ds, new_lyr

Note: this script won't save any attribute information. I'm not familiar with this type of file and don't know how it stores attribute data. In case it does it in the same way a shapefile does, a couple of lines will take care of that as well.


Here is an example code to demonstrate what I mentioned in the comment:

# Simple KML template with `%s` as a place-holder for future text substitution

template = \
r"""<?xml version="1.0" encoding="utf-8" ?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document id="root_doc">

Example code representing collection of placemarks selected from another KML file:

pmarks = \

# Push the content of pmarks into the template
fullkml = (template % pmarks).translate(None, '\n\t\r')

And, fullkml has a complete KML code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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