3

I have hundreds of shapefiles that I have added to a QGIS project. I am using QGIS 3.0.0. I have created a new text field for each of them named 'Enumertr' in PyQGIS and I need to populate this field in each of the shapefiles with the name of the respective layer. I have the below script, but it is bringing an error. I also need to adapt it to iterate through all of the layers in my QGIS project. I am relatively new to Python but am hoping using PyQGIS will save me a substantial amount of time if I can finalise this script.

from PyQt4.QtCore import QVariant
from qgis.core import QgsField, QgsExpression, QgsFeature
vl = iface.activeLayer()
vl.startEditing()
idx = vl.lookupField(‘Enumertr’)
e = QgsExpression (‘vl.name’)
e.prepare(vl.fields())
for f in vl.getFeatures():
 f[idx] = e.evaluate( f )
 vl.updateFeature( f )
vl.commitChanges()
Joseph
76.6k8 gold badges173 silver badges286 bronze badges
asked Jul 16, 2018 at 19:32

1 Answer 1

2

You could use something like the following in the Python Console:

for layer in QgsProject.instance().mapLayers().values():
 with edit(layer):
 for feature in layer.getFeatures():
 feature.setAttribute(feature.fieldNameIndex('Enumertr'), layer.name())
 layer.updateFeature(feature)
answered Jul 17, 2018 at 13:43

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.