0

Is it possible to export multiple layers using for loop?

I want to export all vector layers added to the map.

The problem I experience is that the second argument has to be a string but it leads to overwriting the same file over and over again

error = QgsVectorFileWriter.writeAsVectorFormatV2(vlayer,"D://exportedlayer.shp",transform_context,save_options)

I tried two things:

  1. replacing that string with a variable (layer name)
  2. concatenating file path with layer name ans .shp extension

but none works. Any ideas?

1
  • 1
    They are added to the map, originally come from different xml files stored on the computer.
    – geoplan
    Commented Apr 17, 2023 at 9:06

1 Answer 1

0

Can you try:

layers = [l for l in QgsProject.instance().mapLayers().values() if l.type() == QgsVectorLayer.VectorLayer]
#print(layers)
save_options = QgsVectorFileWriter.SaveVectorOptions()
save_options.driverName = "ESRI Shapefile"
transform_context = QgsCoordinateTransformContext()

for vlayer in layers:
    #print(vlayer.name())
    #print (QgsVectorFileWriter.writeAsVectorFormatV3(vlayer,"D://"+vlayer.name(),transform_context,save_options))
    error, error_string, path, layername = QgsVectorFileWriter.writeAsVectorFormatV3(vlayer,"D://"+vlayer.name(),transform_context,save_options)
    if error != QgsVectorFileWriter.NoError:
        print('Error: {details}'.format(details=error_string))
3
  • Hi Thomas, thank you for the code. Unfortunatelly it also does not do the job. Is it because my vector layers come from xml files? But they are still recognized as vector layers, if i uncomment the second line: print(layers) I get: <QgsVectorLayer: 'D:/...' (ogr)>]
    – geoplan
    Commented Apr 17, 2023 at 9:09
  • It doesn't do the trick. But it works perfectly with a normal shp file, which probably means it' because layers are imported from xml.
    – geoplan
    Commented Apr 17, 2023 at 13:54
  • which QGIS version are you using and what kind of data is it? ALKIS / NAS layer ? even with XML ( NAS/ALKIS-) Layer the snippet works for me in 3.28. just saw that writeAsVectorFormatV2 is seprecated since 3.20 but it still wworks in 3.28.5 ( "Deprecated since version QGIS: 3.20 use writeAsVectorFormatV3 instead" )
    – Thomas B
    Commented Apr 17, 2023 at 15:14

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.