简体   繁体   中英

How do I go to the first record of a CSV file within the same “for” loop?

I had asked a similar question here and the answer that I get was to use the seek() method. Now I am doing the following:

with open("total.csv", 'rb') as input1:
    time.sleep(3)
    input1.seek(0)
    reader = csv.reader(input1, delimiter="\t")
    for row in reader:
       #Read the CSV row by row.

However, I want to navigate to the first record of the CSV within the same for loop . I know that my loop won't terminate that ways but that's precisely what I want. I don't want the for loop to end and if it reaches the last record I want to navigate back to the first record and read the whole file all over again (and keep reading it). How do I do that?

Thanks!

Does it have to be in the for -loop? You could achieve this behaviour like this (untested):

with open("total.csv", 'rb') as input1:
    time.sleep(3)
    reader = csv.reader(input1, delimiter="\t")
    while True:
        input1.seek(0)
        for row in reader:
            #Read the CSV row by row.

For simplicity, create an generator:

def repeated_reader(input, reader):
    while True:
        input.seek(0)
        for row in reader:
            yield row

with open("total.csv", 'rb') as input1:
    reader = csv.reader(input1, delimiter="\t")
    for row in repeated_reader(input1, reader):
        #Read the CSV row by row.

I actually calculated the total number of rows in the CSV and when I was on the last row I did input1.seek(0)

row_count = sum(1 for row in csv.reader(open('total.csv')))
print row_count


row_count2 = 0

with open("total.csv", 'rb') as input1:
        time.sleep(3)
        input1.seek(0)
        reader = csv.reader(input1, delimiter="\t") 
        for row in reader:
            count += 1
            #Read the CSV row by row.
            if row_count2 == row_count:
                row_count2 = 0
                time.sleep(3)
                input1.seek(0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM