I'm trying to make an union with overlapping polygons and save the result in a new shapefile.

from osgeo import ogr
import os
test = ogr.Open(r"F:\Python\Shapefile\BuiltBuf7000.shp")
layer = test.GetLayer()
print layer.GetGeomType()
3 # -> polygons
union_poly = ogr.Geometry(ogr.wkbPolygon)
for feature in layer:
geom =feature.GetGeometryRef()
union_poly = union_poly.Union(geom)

print union_poly

When I run the code I got this result : enter image description here

Now, I would like to save the result in a new shapefile, Does someone know how to do it ?


1 Answer 1


First thing, you need to create an empty shapefile:

# Create datasource.
driver = ogr.GetDriverByName('ESRI Shapefile')
    ds_out = driver.CreateDataSource(filepath)
    raise Exception("File already exists.")

# Grab current layer's SRS and geometry type.
srs = layer_in.GetSpatialRef()
geom_type = layer_in.GetGeomType()

# Create empty layer.
layer_out = ds_out.CreateLayer(name = *name you want*, srs = srs, geom_type = geom_type)

# Copy fields <-- not required.
layer_defn = layer_in.GetLayerDefn()
n_fields = layer_defn.GetFieldCount()
for i in range(n_fields):

or, you know, just load an existing empty shapefile:

driver = ogr.GetDriverByName('ESRI Shapefile')
ds_out = driver.Open(filepath)
layer_out = ds_out.GetLayer()

To save your created polygon:

# Create feature.
layer_defn = layer_out.GetLayerDefn()
feat_out = ogr.Feature(layer_defn)

# Load geometry in feature, and feature in layer.

# Set attributes <-- not required.
feat_to.SetField(field_name, value)

Don't forget to feat_out.Destroy() and ds_out.Destroy() afterwards!

  • Many thanks Roberto, your solution is perfectly working ! I just had to change "layer_in" by "layer" in the layer's SRS function to adapt it
    – DspXav
    Dec 29, 2017 at 11:36

Your Answer

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

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