Aham
Aham

Reputation: 123

QGIS python export all layers of group

in my QGIS project browser I have organized my layers within two groups (test1, test2). Now I would like to export all layers of the group "test1" automatically as csv using python. I found some code to export all layers of the project to csv, that works fine so far:

pathToFile = "C:/Users/xxxx/Documents/test/"
for vLayer in QgsProject.instance().mapLayers().values():
    QgsVectorFileWriter.writeAsVectorFormat( vLayer,  pathToFile+ vLayer.name() + ".csv", "utf-8", vLayer.crs(), driverName="CSV" )

And I found a code to get a list of all layers in the specific group:

mygroup = root.findGroup("test1") 
layer_list= mygroup.findLayers()
layer_list = [layer.name() for layer in mygroup.children()]

Unfortunately I cannot get these two together to export the desired layers. Can anyone help how to do this?

Upvotes: 1

Views: 1690

Answers (1)

bgkarta
bgkarta

Reputation: 11

root = QgsProject.instance().layerTreeRoot()
mygroup = root.findGroup("test1")
layer_list= mygroup.findLayers()
layer_list = [layer.name() for layer in mygroup.children()]
for layer in layer_list:
    print(layer)
    
pathToFile = "C:/Users/xxxx/Documents/test/"
for vLayer in QgsProject.instance().mapLayers().values():
    if vLayer.name() in layer_list:
        print(vLayer.name())
        QgsVectorFileWriter.writeAsVectorFormat( vLayer,  pathToFile+ vLayer.name() + ".csv", "utf-8", vLayer.crs(), driverName="CSV" )

Question is old but, answer probably can help to someone else, it just exporting layers that contains in layer_list. Print is added for better understending what happening. Code can be executed in QGIS up to 3 version in Python console or Python console editor.

Upvotes: 1

Related Questions