Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Importing CSV in Python – why does a for loop over 'data' affect list(data) after it?

I’m importing a simple CSV file. I want to print its content line-by-line and then print it once again, but now as a list of lists representing each line. The following code:

fo = open('filename.csv', 'r')
content = csv.reader(fo)

for each in content:
    print(each)

print("Content as a list: ", list(content))
fo.close()

works as expected for the first task, but then prints an empty list after ‘Content as a list’. If I comment the for loop out, I get the desired result, though. Why does the for loop affect the list(content) below?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

csv.reader function returns an iterator, which can be iterated over only once. How to use csv reader object multiple times

Why can't I iterate twice over the same data?

One of the solutions would be to convert it to a list:

fo = open('filename.csv', 'r')
content = list(csv.reader(fo))
fo.close()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading