3

I'm stuck with a very simple issue.. I've loaded in QGIS (through the py console) a csv layer (no geometry) made of 4 fields and 3 rows:

#load the csv
layer = QgsVectorLayer("path/to/the/csv", "csvlayer", "delimitedtext")
#add it to the TOC
QgsMapLayerRegistry.instance().addMapLayer(layer)

What I'm trying to do is to store the attribute table of the csv layer in a python list. I tried:

for i in layer.getFeatures():
    l = []
    l.append(i.attributes())

it works, but in the list I have only the last row of the attribute table and not all the 3 rows.

How can I have store all the 3 rows as lists in the main list?

Something like:

l
[[1,2,3], [4,5,6], [7,8,9]]

2 Answers 2

3

It is a pure Python question: in your script you initialize the list at each iteration

t = [1,2,3,4]
for i in t:
    l = []
    l.append(i)

 print l 
 [4]

while

 l = []
 for i in t:
     l.append(i)

 print l 
 [1,2,3,4]

or with list comprehensions

l = [i for i in t]

So, your script becomes:

l = [i.attributes() for i in layer.getFeatures()]
0
2

In this order:

l = []
for i in layer.getFeatures():
    l.append(i.attributes())

In your code you have list which is created and overwritten each time.

0

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.