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

Question:

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?

Asked By: dzejkob

||

Answers:

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()
Answered By: Adelina
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.