I'm trying to find the erase geoprocessing method as I am familiar with in ARC, but I can't seem to find it in OGR using Python. I have looked through the module OGR documentation but perhaps I missed it.

An example of the function would be even better.

2 Answers 2


Here is the tool like it is it in ESRI. the input driver could be modified to your needs. Also no projection is enforced on the output currently.

def erase(baseFile, eraseFile, outFile): #this class performs the erase tool from ARCGIS//     erasefile must be polygon
  import os
  import sys
  import functions

    from osgeo import ogr
  except ImportError:
    import ogr

  driver = ogr.GetDriverByName('Mapinfo File')
  driver2 = ogr.GetDriverByName('ESRI Shapefile')

  feat1 = driver.Open(baseFile, 0)
  if feat1 is None:
    print 'Could not open feat1.tab'

  feat2 = driver2.Open(eraseFile, 0)
  if feat2 is None:
    print 'Could not open feat2.tab'

  feat1Layer = feat1.GetLayer()
  feat2Layer = feat2.GetLayer()

  feature2 = feat2Layer.GetFeature(0)
  geomfeat2 = feature2.GetGeometryRef()


  # create a new data source and layer
  fn = outFile
  if os.path.exists(fn):
  outDS = driver.CreateDataSource(fn)
  if outDS is None:
    print 'Could not create file'
  outLayer = outDS.CreateLayer('roads', geom_type=ogr.wkbLineString)

  functions.copyFields(feat1Layer, outLayer)
  # get the FeatureDefn for the output shapefile
  featureDefn = outLayer.GetLayerDefn()

  #loop through input layer
  for inFeature in feat1Layer: 

    # create a new feature
    outFeature = ogr.Feature(featureDefn)

    # copy the attributes and set geometry
    functions.copyAttributes(inFeature, outFeature)

    #get Geometry of feature and apply the difference method on that feature
    inGeom = inFeature.GetGeometryRef()
    GeomDiff = inGeom.Difference(geomfeat2)
    #Set geometry of the outfeature

    # add the feature to the output layer

The OGR function to Erase a geometry is named Difference. I found this Python API document,[osgeo.ogr Python] (http://gdal.org/python/osgeo.ogr-module.html)

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.