Saturday 29 June 2019

qgis - How to fill fields with layer name in PyQGIS


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()

Answer



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)

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...