12

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?

PolyGeo
65.5k29 gold badges115 silver badges349 bronze badges
asked May 25, 2013 at 13:46
8
  • 1
    Here is the same question and the solution [link][1]. [1]: gis.stackexchange.com/questions/43129/… 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 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 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? 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

10

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')
answered Dec 17, 2015 at 12:19
2
  • 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. 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']) Commented Jun 6, 2017 at 9:14

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.