I am trying to convert a GML to an ESRI shapefile using ogr2ogr utility in a python script.

I have successfully installed the GDAL/OGR package via osgeo but I am now struggling to find/understand any details on the syntax for using ogr2ogr in python.

After importing ogr, all I have found is ogr2ogr -f "ESRI Shapefile" output.shp input.gml

How do I use this in python? Is it as simple as assigning the input and output files?

Everything I try I just get syntax errors. Any pointers in the right direction to get me started would be great.

  • what errors are you getting? and what is your GDAL version? pls share for helping to you.. – Aragon Nov 1 '12 at 14:42

Grab a copy of the ogr2ogr Python port, which is distributed with the GDAL source code download or can be found here: http://svn.osgeo.org/gdal/trunk/gdal/swig/python/samples/ogr2ogr.py

Once you import that into your code, you can use it like this:

import ogr2ogr

def main():
  #note: main is expecting sys.argv, where the first argument is the script name
  #so, the argument indices in the array need to be offset by 1
  ogr2ogr.main(["","-f", "KML", "out.kml", "data/san_andres_y_providencia_administrative.shp"])
  • This is the only working example that I've seen anywhere. – bozdoz Mar 25 '14 at 17:15
  • I don't understand, how should I install ogr or GDAL to use it instead of downloading a single py file? – jokoon Jun 24 '20 at 18:40

Read up on os.system or os.popen or subprocess. Or just use ogr2ogr and your shell. Even cmd.exe (Windows) lets you loop over input files.


You will probably find much better answers than I can give you at http://www.gis.usu.edu/~chrisg/python/2009/lectures/ospy_slides1.pdf and http://trac.osgeo.org/gdal/wiki/GdalOgrInPython.

Try there or another tutorial linked from the second URL and maybe ask another more specific question if you are stuck.


A detailed explanation how to substitute the ogr2ogr command line tool with the OGR Python API can be found here.

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.