Create any nonempty csv file and call this test.csv. Consider the code
import csv
with open("test.csv") as read_file:
#this test case also applies to csv.reader()
check_file = csv.DictReader(read_file)
#1) with a nonempty csv file, this will return a nonempty output
for row in check_file:
print(row)
#2) this will not return any output
for row in check_file:
print(row)
In other words, what has happened is that the iteration over rows of check_file
has deleted all data in check_file
, such that 1) returns nonempty output but the exact same function 2) returns no output at all.
There is a simple, but inelegant, solution:
import csv
with open("test.csv") as read_file:
#this test case also applies to csv.reader()
check_file = csv.DictReader(read_file)
#1) with a nonempty csv file, this will return a nonempty output
for row in check_file:
print(row)
with open("test.csv") as read_file:
check_file = csv.DictReader(read_file)
#2) this will return the same output as 1)
for row in check_file:
print(row)
What is the explanation for this odd behaviour?