PyQGIS Export – How to Export WKT to CSV from QgsVectorLayer

csvpyqgiswell-known-text

I'm trying to export QgsVectorLayer format into a csv with WKT?

I'm really have a hard time understanding the QGIS python documentation. I don't even see any option for Geometry. Even though I saw other people use it on stackexchange.
https://api.qgis.org/api/classQgsVectorFileWriter_1_1SaveVectorOptions.html#ad98c015173618ad5a4729af18eeace82
Can anyone help me with the correct formatting and is this even possible.

The code works, it's just I never see the WKT in the csv, unless I do it manually from QGIS.

output_file_name = self.parameterDefinition('input_boundary').valueAsPythonString(parameters['input_boundary'], context).replace("'","")

boundary_layer = QgsVectorLayer(output_file_name,'boundary','ogr')        
#df = pd.read_csv(points_file, encoding='iso-8859-1')
options = QgsVectorFileWriter.SaveVectorOptions()
options.driverName = "csv"
options.fileEncoding = "utf-8"
options.GEOMETRY="AS_WKT"
#options.geometry="AS_WKT"
#options.destCRS =
#options.ct =
boundary_csv_path = os.path.join(work_space_path,"test8.csv")

QgsVectorFileWriter.writeAsVectorFormatV3(boundary_layer,boundary_csv_path,QgsProject.instance().transformContext(),options)
#QgsVectorFileWriter.writeAsVectorFormat(boundary_layer, boundary_csv_path, "utf-8", None, "CSV", layerOptions =['GEOMETRY=AS_XY'])

Best Answer

You can use this structure:

....
....
options = QgsVectorFileWriter.SaveVectorOptions()
options.driverName = "csv"
options.fileEncoding = "utf-8"
options.layerOptions = ['GEOMETRY=AS_WKT']

transform_context = QgsProject.instance().transformContext()

boundary_csv_path = os.path.join(work_space_path,"test8.csv")
QgsVectorFileWriter.writeAsVectorFormatV3(boundary_layer,
                                          boundary_csv_path,
                                          transform_context,
                                          options)

You can add additional layer options within a list as follows:

options.layerOptions = ['GEOMETRY=AS_WKT',
                        'SEPARATOR=TAB',
                        'CREATE_CSVT=YES']

enter image description here

Related Question