4

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)
1
  • 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 shared Commented Jan 20, 2022 at 14:08

2 Answers 2

6

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)
``
3
  • Great! It's the desired answer. I'm grateful to you bro! Commented 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 you Commented Jan 21, 2022 at 9:14
  • gis.stackexchange.com/q/242553/29431 Commented Jan 21, 2022 at 9:38
3

One easy way is to execute Refactor field manually. Add the field and calculate with the expression now(), and delete whatever fields you like:

enter image description here

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'})
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.