Reputation: 517
import csv
def csv_reader(file_obj):
reader = csv.reader(file_obj)
# for row in reader:
# print(" ".join(row))
reader_2 = csv.DictReader(file_obj, delimiter=",")
for row_2 in reader_2:
print(row_2)
csv_path = "data.csv"
with open(csv_path, "r") as f_obj:
csv_reader(f_obj)
I can't figure out why the second "for loop" only prints any text if the first "for loop" is commented out.
Upvotes: 0
Views: 67
Reputation: 95908
It's because you are passing the same file handler to both csv
reader objects. Once you iterate over it once, you have to manually do file_obj.seek(0)
for it to work as intended, or else it simply acts like an empty file.
Upvotes: 2
Reputation: 9427
The CSV reader has already consumed your file.
Calling file_obj.seek(0)
before using it again should do the trick.
Alternatively, opening (and then closing) the file for each operation will also work.
Upvotes: 4