I've only recently started using QGIS and it's Python API. Currently I've loaded two OpenStreetMap datasets. I would like to remove lines with from the second set where the name is already present in the first. There is a catch: the first dataset uses a field called name1 while the second dataset uses a field called Name.

What I've tried so far is fairly naive and non-pythonic:

  1. Store a list of all the values called name1 from the first dataset
  2. Iterate through all the fields in the second dataset and if Name attribute is contained in the name1 values array above, call QgsVectorLayer's deleteFeature() passing the feature's id()

In code, the layer I want to delete from is called Cropped and the list of all values called name1 from the first dataset is called roads so what I tried looks like this:

fields = Cropped.getFeatures()
for f in fields:
    name = f.attribute('Name')
    count = roads.count(name)
    if count > 0:
        print 'removing ',name,count

startEditing() and commitChanges() return True, but all Cropped.deleteFeature(f.id()) calls return False.

I've also spotted this existing post on How to delete selected features in Qgis using Python which seems to tackle the exact problem. I am using QGIS version 2.14.0-Essen so I have tried this, based on the answer:

with edit(Cropped):
    for fid in fids:

Where fids is a list of field ids that match the condition above. I get False for every single call.

Any hints/tips on what I'm doing wrong/missing ?


1 Answer 1


Some vector formats are read-only in QGIS. So, first check if your Cropped layer is read-only:


If not, then you could use this code snippet to delete all features whose Name attribute value is already in the roads list (note the handy function to delete all those features in a single step):

features = Cropped.getFeatures()
ids = [ f.id() for f in features if f.attribute( 'Name' ) in roads ]
with edit( Cropped ):
    Cropped.deleteFeatures( ids )
  • That sounds very promising (+1). I can check in a few hours. In case the Cropped layer is a read-only vector format, what's the best way to make them writeable ? (Had a quick peek at the manual and Toggle Editing seems like it should work) Commented Apr 26, 2016 at 20:58
  • In case it's read-only, you could export it to a writeable format, such as Shapefile (I still don't know what your layer format is). Right click on the layer and click on "Save As...". Commented Apr 26, 2016 at 21:02
  • 1
    "Save as..." shape file worked like a charm, thank you :) Commented Apr 27, 2016 at 17:55

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.