Reputation: 363
Why is the following code returning the output twice? I know I need to use print(line) instead of print(row) but I am just curious as to why print(row) is returning the output twice?
with open ('data.csv','r') as data:
reader = csv.DictReader(data)
row = next(reader)
for line in reader:
print(row)
OUTCOME:
OrderedDict([('\ufeffProgramming language', 'Python'), ('Designed by', 'Guido van Rossum'), ('Appeared', '1991'), ('Extension', '.py')])
OrderedDict([('\ufeffProgramming language', 'Python'), ('Designed by', 'Guido van Rossum'), ('Appeared', '1991'), ('Extension', '.py')])
Upvotes: 0
Views: 744
Reputation: 117691
row = next(reader)
first reads out the first line of the CSV.
Then you have print(row)
instead of print(line)
in the loop body and thus it repeatedly prints the first line of the CSV for each other line. In this case there are two other lines in the CSV file, so it prints twice.
Upvotes: 1