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"
2
-
2Does this answer help? gis.stackexchange.com/q/109078/43 – Richard Morgan Mar 29 '16 at 16:07
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
-
@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()
andlayer.commitChanges()
do nothing if the nested calls are on the dataprovider. rather uselayer.deleteAttribute(idx)
instead. And if you want to have it extra-nice you can usewith edit(layer)
instead :) (reference: opengis.ch/2015/08/12/with-edit-layer) – Matthias Kuhn Apr 1 '16 at 7:23 -
1That's probably caused by the indexes changing while removing fields. Better iterate in reverse order. And still, if using
startEditing()
orwith edit
don't usedataProvider()
at all - or skip thestartEditing()
/with edit
part ;) – Matthias Kuhn Apr 1 '16 at 10:29 -
1One last hint: use
layer.fields()
(or for older qgis versionslayer.pendingFields()
) or you may have troubles with joined and virtual fields. – Matthias Kuhn Apr 1 '16 at 10:49