I have the following script to merge a group of layers, and I want to edit the script to add a field containing today's date in the attribute table and also delete some fields by their names?
root = QgsProject.instance().layerTreeRoot()
group = root.findGroup("RL")
layers = [layer.layer() for layer in group.children()]
merged = processing.run("native:mergevectorlayers",
{'LAYERS': layers, 'OUTPUT':"TEMPORARY_OUTPUT"})["OUTPUT"]
QgsProject.instance().addMapLayer(merged, False)
root.insertLayer(0, merged)
Kadir Şahbaz
78.6k57 gold badges260 silver badges407 bronze badges
asked Jan 20, 2022 at 13:49
-
we can add the date with the advanced python field calculator, but I want to add it with a python script and this is not shown in the link you sharedAhmed Kamel– Ahmed Kamel2022年01月20日 14:08:16 +00:00Commented Jan 20, 2022 at 14:08
2 Answers 2
You can use this script:
from datetime import date
#
# previous lines
#
provider = merged.dataProvider()
## add date field
i = merged.fields().indexFromName("date")
if i == -1:
provider.addAttributes([QgsField('date', QVariant.Date)])
merged.updateFields()
##
## populate date field
i = merged.fields().indexFromName("date")
attr_map = {f.id(): {i: QDate(date.today())} for f in merged.getFeatures()}
provider.changeAttributeValues(attr_map)
##
## delete some fields
field_names = ['Shape'] # field names to be deleted
field_indices = [merged.fields().indexFromName(f) for f in field_names]
provider.deleteAttributes(field_indices)
merged.updateFields()
##
QgsProject.instance().addMapLayer(merged, False)
root.insertLayer(0, merged)
``
answered Jan 20, 2022 at 23:48
-
Great! It's the desired answer. I'm grateful to you bro!Ahmed Kamel– Ahmed Kamel2022年01月21日 08:35:04 +00:00Commented Jan 21, 2022 at 8:35
-
It's working well, How can I set the name of the resulted merged layer to be "RL_Dozers" because I run the script for two groups and I want to differentiate them? I'm sorry I burdened youAhmed Kamel– Ahmed Kamel2022年01月21日 09:14:24 +00:00Commented Jan 21, 2022 at 9:14
-
gis.stackexchange.com/q/242553/29431Kadir Şahbaz– Kadir Şahbaz2022年01月21日 09:38:18 +00:00Commented Jan 21, 2022 at 9:38
One easy way is to execute Refactor field manually. Add the field and calculate with the expression now(), and delete whatever fields you like:
Then press Ctrl+Alt+H and copy paste the code:
processing.run("native:refactorfields", {'INPUT':'C:/GIS/data/tempdata/grid.shp','FIELDS_MAPPING':[{'expression': '\"id\"','length': 20,'name': 'id','precision': 0,'type': 6},{'expression': '\"left\"','length': 23,'name': 'left','precision': 15,'type': 6},{'expression': '\"top\"','length': 23,'name': 'top','precision': 15,'type': 6},{'expression': '\"right\"','length': 23,'name': 'right','precision': 15,'type': 6},{'expression': '\"bottom\"','length': 23,'name': 'bottom','precision': 15,'type': 6},{'expression': 'now()','length': 0,'name': 'now','precision': 0,'type': 14}],'OUTPUT':'TEMPORARY_OUTPUT'})
answered Jan 20, 2022 at 14:01
lang-py