2

I would like to delete all fields with the string "RAWI". For instance the field "RAWI_WA" and the field "RAWI_BO" should be deleted but not the field "NSG_RAW"

3

You can use the following code in the Python console which, for your selected layer, deletes all fields which contains RAWI in the field name:

layer = qgis.utils.iface.activeLayer()
# Get field names of layer
field_names = [field.name() for field in layer.fields()]

# Use `with edit()` method to edit and commit changes in one go
with edit(layer):
    # Assign count in reverse order for each field which will be used as index
    for i, j in reversed(list(enumerate(field_names))):
        if "RAWI" in j:
            layer.deleteAttribute(i)
  • 1
    Lovely use of enumerate to get the index and item. – Richard Morgan Mar 30 '16 at 12:46
  • @RichardMorgan - Thank you :) I'm sure there's a nicer way of getting the indices for the relevant fields! – Joseph Mar 30 '16 at 12:49
  • 1
    layer.startEdiging() and layer.commitChanges() do nothing if the nested calls are on the dataprovider. rather use layer.deleteAttribute(idx) instead. And if you want to have it extra-nice you can use with edit(layer) instead :) (reference: opengis.ch/2015/08/12/with-edit-layer) – Matthias Kuhn Apr 1 '16 at 7:23
  • 1
    That's probably caused by the indexes changing while removing fields. Better iterate in reverse order. And still, if using startEditing() or with edit don't use dataProvider() at all - or skip the startEditing() / with edit part ;) – Matthias Kuhn Apr 1 '16 at 10:29
  • 1
    One last hint: use layer.fields() (or for older qgis versions layer.pendingFields()) or you may have troubles with joined and virtual fields. – Matthias Kuhn Apr 1 '16 at 10:49

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.