PyQGIS – Exporting Feature Attributes and Coordinates to CSV

csvexportpyqgis

I've retrieved some attributes and coordinates from a point layer in QGIS:

path_file = myfile
layer = QgsVectorLayer(path_file, "name", "ogr")
QgsProject.instance().addMapLayer(layer)
features = layer.getFeatures()
for f in features:
    point = f.geometry().asPoint()
    x = point.x()
    y = point.y()

and I'd like to export "ID", "x", and "y" values into a CSV file, possibly one for a column. I tried with .write() but couldn't get a good output. Any help?

Best Answer

Use this script:

import csv

path_file = myfile
csv_file_path = 'path/to/csv_file.csv'

layer = QgsVectorLayer(path_file, "name", "ogr")
QgsProject.instance().addMapLayer(layer)

# open the file in the write mode
csv_file = open(csv_file_path, 'w')
# create the csv writer
writer = csv.writer(csv_file)

features = iface.activeLayer().getFeatures()
for f in features:
    point = f.geometry().asPoint()
    x = point.x()
    y = point.y()
    # write a row to the csv file
    writer.writerow([f["ID"], x, y])

# close the file
csv_file.close()