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"
Asked
Active
Viewed 799 times
3
-
2Does this answer help? http://gis.stackexchange.com/q/109078/43 – Richard Morgan Mar 29 '16 at 16:07
1 Answers
6
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)
Joseph
- 75,746
- 7
- 171
- 282
-
2
-
@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
-
2
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: http://www.opengis.ch/2015/08/12/with-edit-layer/) – Matthias Kuhn Apr 01 '16 at 07:23 -
@MatthiasKuhn - Thank you =). I've used the
with edit(layer):method as you suggested, however I seem to be having issues withlayer.deleteAttribute(). If I put this inside theifloop, it only deletes half of the fields each time the code is run. Guess I missed something... ;) – Joseph Apr 01 '16 at 10:25 -
2That's probably caused by the indexes changing while removing fields. Better iterate in reverse order. And still, if using
startEditing()orwith editdon't usedataProvider()at all - or skip thestartEditing()/with editpart ;) – Matthias Kuhn Apr 01 '16 at 10:29 -
@MatthiasKuhn - Ahh you're a genius! Many thanks for your valuable lesson :) – Joseph Apr 01 '16 at 10:42
-
2One last hint: use
layer.fields()(or for older qgis versionslayer.pendingFields()) or you may have troubles with joined and virtual fields. – Matthias Kuhn Apr 01 '16 at 10:49 -
I tried the
with edit(layer):in the console and it worked great. It does not seem to work in a plugin. Does anyone know what is missing for the plugin? – Cary H Apr 02 '20 at 13:36