1

I know basic python, but am struggling to learn how to use it with QGIS. I have a polygon shapefile that maps the presence/absence of various species. Each species has a column in the attribute table a- if the species is present in the polygon then the species name is in the cell, otherwise "null". I have a dictionary of fullname:abbreviation which I use to create a string for each row of abbreviations so that all the data for each row is represented in a single field.

The script seems to work, but when I tried to use the shapefile in ArcGIS the new column was empty. I saved the edits afterward. Can anyone tell me what I'm missing?

from PyQt4.QtCore import QVariant

subs = {'Argent & Sable':'AS',
'Barbastelle':'Bbl',
'Barred Tooth-striped':'BTs',
}
#etc etc      


layer = iface.activeLayer()
layer.startEditing()
iter = layer.getFeatures()

for feature in iter:
    newStr = ''
    for field in feature.attributes():
        if field == 'NULL':
            pass
        else:
            if field in subs.keys():
                newStr += subs[field] + ', '

    feature['Species'] = newStr
    layer.updateFeature(feature)
  • Welcome to GIS:SE @user2980115! Do the correct values appear when you look at the attribute table in QGIS after you have saved the edits? – Joseph Feb 16 '16 at 15:10
  • I will have to check when I get home. I ran the script and used the values in QGIS but haven't tried closing and reopening the project in QGIS. I only encountered the problem when I came to work where I only have access to ArcGIS. – user2980115 Feb 16 '16 at 15:24
  • Ok, I've checked and it works fine in QGIS even if I bring it into a new project. – user2980115 Feb 16 '16 at 20:01
2

You are missing a call to actually save the changes back to the layer. At the end of your script you need to add:

layer.commitChanges()

See http://qgis.org/api/classQgsVectorLayer.html#afab34baf331320a8c3212993f5fccfa1

  • 2
    @user2980115 - You should accept this answer (click the green-faded tick on the left-hand side) to mark this question as answered =) – Joseph Feb 18 '16 at 10:29

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.