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
1 Answer 1
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
lang-py
print("ID: %d; XY coordinates: %f, %f" % (f['ID'], x, y))
, but maybe I didn' get the point of your comment