PyQGIS Export – How to Export Attribute Table to CSV via Pure Python in QGIS

attribute-tablecsvexportpyqgis

I would like to use pure Python to export the attribute table as csv. For the variable data, I need a list that will read the whole attribute table. Is that possible?

import csv

layer = iface.activeLayer()
header = [field.name() for field in layer.fields()]
print(header)
data = [
    #Can I get the attribute table of the active layer here as a list
]

with open('//home/lissiklaus/Downloads/tmp/csv/countries.csv', 'w', encoding='UTF8', newline='') as f:
    writer = csv.writer(f)

    # write the header
    writer.writerow(header)

    # write multiple rows
    writer.writerows(data)

Best Answer

You can use .getFeatures() to iterate over each feature and .attributes() to fetch each feature's attributes:

layer = iface.activeLayer()
fieldnames = [field.name() for field in layer.fields()] #If you need the fieldnames

attributes = []
for f in layer.getFeatures():
    attrs = f.attributes()
    #attrs is a list of current features attributes, for example 
    #[1, 561, 'Järnvägsstation', 0.0, 'Riksgränsen', NULL, '2012-03-29 12:56']
    attributes.append(attrs)

#attributes is now a list of lists:
#attributes[:2]
#[[1, 561, 'Järnvägsstation', 0.0, 'Riksgränsen', NULL, '2012-03-29 12:56'], 
# [2, 561, 'Järnvägsstation', 0.0, 'Katterjåkk', NULL, '2012-03-29 12:56']]

print("Done")

enter image description here

Related Question