[GIS] Writing vector layer to CSV file with geometry using PyQGIS

csvfields-attributesgeometrypyqgis

I use Python try to write vector layer file to csv file with this code:

QgsVectorFileWriter.writeAsVectorFormat(mylayer, r'c:\temp\xyz.csv', "utf-8", None, "CSV")

It can export to xyz.csv but only attributes show in the csv, not the geometry column.

How can I export both attribute and spatial data into csv file?

Best Answer

A similar answer was provided from this post:

Save as .csv with coordinates in both QGIS 2.2 and PyqGIS

Just add layerOptions ='GEOMETRY=AS_XYZ at the end:

layer = QgsVectorLayer("path/to/shapefile", "name", "ogr")
QgsVectorFileWriter.writeAsVectorFormat(layer, r'c:\temp\xyz.csv', "utf-8", None, "CSV", layerOptions='GEOMETRY=AS_XYZ')