4

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)

2 Answers 2

7

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

1
  • I prefer pure python because i later use LibreOffice-Base to establish a database-connection and create pivot evaluations in calc. only with python do the numeric properties of certain fields remain in lo-base.
    – Klaus
    Commented May 19, 2023 at 10:11
3

I use this:

import csv

outFolder = r'/home/lissiklaus/Downloads/tmp/csv/'
filename = 'countries.csv'
outPath = f"{outFolder}{filename}"

layer = iface.activeLayer()
header = [field.name() for field in layer.fields()]

myFeatures = layer.getFeatures()
data = [f for f in myFeatures]

with open(outPath, 'w', encoding='UTF8', newline='') as f:
    writer = csv.writer(f)

    # write the header
    writer.writerow(header)

    # write multiple rows
    writer.writerows(data)

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.