4

I have a QGIS graphical model which takes point data and generates multiple temporary layers; some are lines, some are polygons. I have them in subgroups in my QGIS project.

I would like a quick way of clicking on the subgroup and saving to a directory using the CRS of the project, and naming each layer as it's current name.

Even better; if I can add the DDMM date to the end of the filename.

0

1 Answer 1

6

This is working if you manually change the layer group name by editing line 7:

import datetime, os

out_folder = r'/home/bera/Desktop/tempgis/shapes/'
yearmonth = datetime.datetime.today().strftime('%y%m')

root = QgsProject.instance().layerTreeRoot()
subname = 'sub-group1' #Change this to the subgroupname

options = QgsVectorFileWriter.SaveVectorOptions()
options.driverName = "ESRI Shapefile"

for child in root.findGroup(subname).children():
    if isinstance(child, QgsLayerTreeLayer): #For each layer, save as shapefile
        print(child.name())
        coordinateTransformContext=QgsProject.instance().transformContext()
        options.ct = QgsCoordinateTransform(child.layer().crs(),QgsProject.instance().crs(), coordinateTransformContext)
        out_file = os.path.join(out_folder, child.layer().name()+'_{}.shp'.format(yearmonth))
        QgsVectorFileWriter.writeAsVectorFormatV2(child.layer(), out_file, coordinateTransformContext, 
        options)

enter image description here

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.