2

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?

Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389
DGIS
  • 2,527
  • 16
  • 36

3 Answers3

2

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.

DGIS
  • 2,527
  • 16
  • 36
0

The answer is posted here

The third parameter should be layer.crs()

Mohammad ElNesr
  • 272
  • 2
  • 7
0

If you are using a 3.0+ version of QGIS then you will have to change writeAsVectorFormat to writeAsVectorFormatV2, which means you are going to need new parameters(transformContext(), SaveVectorOptions()). So it should be something like that:

options = QgsVectorFileWriter.SaveVectorOptions()
options.driverName = 'utf-8'
options.fieldNameSource = QgsVectorFileWriter.Original

error, error_string = QgsVectorFileWriter.writeAsVectorFormatV2(lyr, outputPath, QgsProject.instance().transformContext(), options)