3

I wrote the code below to save selected layers in the layerTree to a folder by Python, some of them are temporary layers, I don't know if it matters, and my main purpose is to save those temporary layers altogether. The code executed without error, but nothing in the direct folder:

for lyrs in iface.layerTreeView().selectedLayers():
    path = "C:/Users/xxx/Documents/A_work/Scripts"
    os.chdir(path)
    basename=lyrs.name()
    SHPname = basename +'.shp'
    SHPpath= path + '/' + SHPname
    QgsVectorFileWriter.writeAsVectorFormat(lyrs,SHPpath,'utf-8',lyrs.crs(),'SHP', layerOptions=['ESRI Shapefile'])

2 Answers 2

7

Driver name parameter should be 'ESRI Shapefile' instead of 'SHP' for shapefiles. And no need layerOptions here.

Change

QgsVectorFileWriter.writeAsVectorFormat(
    lyrs,SHPpath,'utf-8',lyrs.crs(),'SHP', layerOptions=['ESRI Shapefile'])

to

QgsVectorFileWriter.writeAsVectorFormat(
    lyrs, SHPpath, 'utf-8', lyrs.crs(), 'ESRI Shapefile')
0
6

and in addition to Kadir: you should use writeAsVectorFormatV3 since QGIS Version 3.20. The code then looks like

for lyrs in iface.layerTreeView().selectedLayers():
   path = "C:/tonne/test"
   os.chdir(path)
   basename=lyrs.name()
   SHPname = basename +'.shp'
   SHPpath= path + '/' + SHPname
   options = QgsVectorFileWriter.SaveVectorOptions()
   options.driverName = 'ESRI Shapefile'
   context = QgsProject.instance().transformContext()
   # since QGIS 3.20 you should use writeAsVectorFormatV3
   QgsVectorFileWriter.writeAsVectorFormatV3(lyrs, SHPpath, context, options)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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