Home > Net >  Importing CSV in Python - why does a for loop over 'data' affect list(data) after it?
Importing CSV in Python - why does a for loop over 'data' affect list(data) after it?

Time:12-30

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?

CodePudding user response:

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()
  • Related