PyQGIS Error – Troubleshooting QgsVectorFileWriter.writeAsVectorFormat() Argument Mismatch

pyqgispyqgis-3

The following code iterates through a folder of .xyz files and is supposed to copy them into another folder.

for file in glob.glob("*.xyz"):
    uri = "file:///" + inputDir +"/"+ file + "?type=csv&delimiter=%s&crs=%s&xField=%s&yField=%s" % (" ", crs, "field_1", "field_2")
    name = file.replace('.xyz', '')
    lyr = QgsVectorLayer(uri, name, "delimitedtext")
    outputPath = outDir + file
    QgsVectorFileWriter.writeAsVectorFormat(lyr, outputPath, 'utf-8', lyr.crs(), "CSV", layerOptions='GEOMETRY=AS_XYZ')

However, I get the following error message:

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

Traceback (most recent call last): File
"C:/Users/denni/AppData/Roaming/QGIS/QGIS3\profiles\default/python/plugins\Clip_XYZ\Clip_XYZ.py",
line 283, in run
self.moveFiles() File "C:/Users/denni/AppData/Roaming/QGIS/QGIS3\profiles\default/python/plugins\Clip_XYZ\Clip_XYZ.py",
line 251, in moveFiles
QgsVectorFileWriter.writeAsVectorFormat(lyr, outputPath, 'utf-8', lyr.crs(), "CSV", layerOptions='GEOMETRY=AS_XYZ') TypeError:
QgsVectorFileWriter.writeAsVectorFormat(): arguments did not match any
overloaded call: overload 1: argument 'layerOptions' has unexpected
type 'str' overload 2: argument 4 has unexpected type
'QgsCoordinateReferenceSystem' overload 3: argument 3 has unexpected
type 'str'

I don't understand the error. When I check the documentation, layerOptions is a str, argument 4 is the crs, and argument 3 is also a str.

Are the docs wrong? Or is there something else wrong with my code?

Best Answer

Ok, I found the answer. layerOptions expects a list of strings. Thus, layerOptions=['GEOMETRY=AS_XYZ']is correct.

I still don't get the error for overload 2 and 3 though. But now these errors don't appear anymore.