0

I am trying to export all active layers in a QGIS project to a specified folder, below is what I get atm

Outputdir='C:/Users/DN/Downloads/Test/'


layer = iface.activeLayer()

QgsVectorFileWriter.writeAsVectorFormat( layer, Outputdir + layer.name() + ".shp", "utf-8", layer.crs(), "ESRI Shapefile", 1)

It only works when I click on the layer that I want to export, I am wondering if it's possible to write a loop to loop through all active layers in the project and export them.

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
Zhifang Hu
  • 151
  • 2
  • There is only one 'active layer', it's the one you've clicked on. https://gis.stackexchange.com/questions/26257/iterating-over-map-layers-in-qgis-python might help with your problem. – Michael Stimson Nov 19 '19 at 05:06
  • I wonder if OP means all checked layers... in which case the likely duplicate is: https://gis.stackexchange.com/questions/152537/programmatically-get-selected-layers-from-the-qgis-legend/152544 – Ben W Nov 19 '19 at 06:17

1 Answers1

3

To iterate over all layers in the project and export them to a specified folder do the following:

We need identify all layers in the project using iface.mapCanvas().layers(). Then we can loop over the layers and export them.
Outputdir is the name of the folder where you would like to save to.

Outputdir = 'C:/temp/'

layers = iface.mapCanvas().layers()
for layer in layers:
    layerType = layer.type()
    if layerType == QgsMapLayer.VectorLayer:
        print (layer.name())
        QgsVectorFileWriter.writeAsVectorFormat( layer, Outputdir + layer.name() + ".shp", "utf-8", layer.crs(), "ESRI Shapefile" )
Cushen
  • 2,928
  • 13
  • 15