Search code examples
pythonloopsdictionarycsvreader

how to tell the for loop to read a file from the start?


While reading the CSV file in these lines:

csv_file = open(sys.argv[1], "r")  # reading the csv file into memory
csv_reader = csv.DictReader(csv_file)

When I tried to make a copy of the csv_reader while using the for loop it worked, but any changes to that copy version affected the csv_reader variable, plus

for line in csv_reader:
    copy = line 
    break

for line in csv_reader:
    print(line)

the second for loop will print everything except for the first line in thencsv_file, why?


Solution

  • You can use csv_file.seek(0) in between your for loops.

    csv_file = open(sys.argv[1], "r")
    csv_reader = csv.DictReader(csv_file)
    
    for line in csv_reader:
        copy = line 
        break
    
    csv_file.seek(0)
    
    for line in csv_reader:
        print(line)
    # Outputs full csv file