Home > Blockchain >  Can't iterate over csv file after calling list()
Can't iterate over csv file after calling list()

Time:10-12

When using list() to find the line count of the csv file, I am unable to iterate over the csv after.

This is working:

with open(data, 'r') as f_csv:
     csv_file = csv.reader(f_csv)
     for row in csv_file:
         print(row)

This is not working:

with open(data, 'r') as f_csv:
     csv_file = csv.reader(f_csv)
     print(len(list(csv_file)))
     for row in csv_file:
         print(row)

CodePudding user response:

This is because when you call list(csv_file), this exhausts the file and moves the file pointer to the end of file as csv.reader returns an iterator that loops over each line until EOF is reached.

Perhaps store list(csv_file) in a variable and loop over that, or you can call f_csv.seek(0) before the loop to return the file pointer back to the start of the file.

with open(data, 'r') as f_csv:
    csv_file = csv.reader(f_csv)
    print(len(list(csv_file)))
    f_csv.seek(0)
    for row in csv_file:
        print(row)

CodePudding user response:

You must either create a second reader, seek to the beginning of the iterator with f_csv.seek(0), or read the contents into a variable. Once you call list() on it, you are at the end of the reader.

with open("sample.csv", "r") as f_csv:
    reader = csv.reader(f_csv)
    data = [row for row in reader]
    print(len(data))
    for row in data:
        print(row)

This is an example, and here is example of using seek:

with open("sample.csv", "r") as f_csv:
    reader = csv.reader(f_csv)
    print(len(list(reader)))
    f_csv.seek(0)
    for row in reader:
        print(row)
  • Related