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?

Kadir Şahbaz
78.6k57 gold badges260 silver badges407 bronze badges
asked Apr 4, 2022 at 16:16
4
  • 1
    there is no sign of you writing the variables out in your code example 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 Commented Apr 4, 2022 at 16:25
  • Well try printing to a file instead of the screen, not sure I see your problem 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 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()
answered Apr 15, 2022 at 7:49

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.