PyQGIS – Saving Layer as Shapefile

pyqgissaveshapefilevector-layerwriters

Using QGIS 3.4.4, I'm trying to save a layer as shapefile with the following code:

import os
import qgis.core

working_folder = r'C:\myFolder'
fc_Prospect = os.path.join(working_folder, Equipment.gdb|layername=Prospect) 
layer1 = QgsVectorLayer(fc_Prospect, 'Prospect', 'ogr')
       
path = r'C:\myFolder\test.shp'
_writer = QgsVectorFileWriter.writeAsVectorFormat(layer1,path,'utf-8','ESRI Shapefile')

However, I am getting this error:

TypeError: QgsVectorFileWriter.writeAsVectorFormat(): arguments did
not match any overloaded call:
overload 1: argument 4 has unexpected
type 'str'
overload 2: argument 4 has unexpected type 'str'
overload 3: argument 3 has unexpected type 'str'

I am quite new with python, so I am not sure what this error means. I've been checking documentation at https://qgis.org/pyqgis/master/core/QgsVectorFileWriter.html#qgis.core.QgsVectorFileWriter.writeAsVectorFormat, but it didn't really help.

Best Answer

Looking at the documentation suggests that it is expecting these parameters:

Parameters:

layer – layer to write

fileName – file name to write to

fileEncoding – encoding to use

destCRS – CRS to reproject exported geometries to, or invalid CRS for no reprojection

driverName – OGR driver to use

onlySelected – write only selected features of layer

errorMessage – pointer to buffer fo error message

datasourceOptions – list of OGR data source creation options

layerOptions – list of OGR layer creation options

skipAttributeCreation – only write geometries

newFilename – QString pointer which will contain the new file name created (in case it is different to fileName).

symbologyExport – symbology to export

symbologyScale – scale of symbology

filterExtent – if not a null pointer, only features intersecting the extent will be saved (added in QGIS 2.4)

overrideGeometryType – set to a valid geometry type to override the default geometry type for the layer. This paramet

So your error says it is expecting the 4th parameter to be a CRS not a string.

I suspect that means you should write your call as:

_writer = QgsVectorFileWriter.writeAsVectorFormat(layer1,path,'utf-8',driverName='ESRI Shapefile')