6

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?

4
  • 1
    there is no sign of you writing the variables out in your code example
    – Ian Turton
    Commented Apr 4, 2022 at 16:18
  • @IanTurton, I've used the code just to print the values on screen with print("ID: %d; XY coordinates: %f, %f" % (f['ID'], x, y)), but maybe I didn' get the point of your comment
    – HyPhens
    Commented Apr 4, 2022 at 16:25
  • Well try printing to a file instead of the screen, not sure I see your problem
    – Ian Turton
    Commented Apr 4, 2022 at 16:46
  • That's exactly what I'm asking for, actually. A formatted .csv with a column for every value
    – HyPhens
    Commented Apr 4, 2022 at 19:38

1 Answer 1

10

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()

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.