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?

  • 1
    Here is the same question and the solution [link][1]. [1]: gis.stackexchange.com/questions/43129/…
    – mete7
    Commented May 25, 2013 at 15:00
  • I'm sorry for make question not clear. my work use python with pyqgis write vector layer to csv file. I want csv file have geometry but it not. still need answer
    – Anubiz
    Commented May 26, 2013 at 7:55
  • Depends on what type of vector layer you want to export. For point layer you could just add the lat, long values as attribute table columns. For all others you need WKT
    – Curlew
    Commented May 26, 2013 at 8:39
  • Thank you Curlew, I work with point and polygon layer. for point layer you mean add lat, lon column in attribute table? how about polygon?
    – Anubiz
    Commented May 27, 2013 at 8:39
  • 3
    Is this really a duplicate? This question here is aimed particularly at python, which is not covered by the linked answer. Commented Jun 10, 2013 at 8:18

1 Answer 1


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')
  • Hi, I am facing a problem in this, If I type this in console it does not save the Spatial data but only the attributes. But if I save it manually it works. I am using QGIS 2.14.12.
    – Sunny Naik
    Commented Jun 6, 2017 at 6:14
  • 2
    @SunnyNaik - The layerOptions parameter now requires a list of string values whereas before a single value was enough (as described in this post). So your last line would look like: QgsVectorFileWriter.writeAsVectorFormat(layer, r'c:\temp\xyz.csv', "utf-8", None, "CSV", layerOptions=['GEOMETRY=AS_XYZ'])
    – Joseph
    Commented Jun 6, 2017 at 9:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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