Python Forum

Full Version: Continuously iterating through a csv file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hi, I am writing python code that reads values from a csv file, I have the reading down but when the program reaches the end of the csv I need it to start from the top. So it will continuously read the data over and over until I tell it to stop.

here is my current reader code
  
csvname=input("Enter the csv file path : \n")
    with open(csvname, 'rt') as f:
                reader= csv.DictReader(f)
                while True: 
                    while mainFlag==True:
                        start_time = time.monotonic()       
                        for row in reader :                       
                                interger= int(row['setpos'])
                                print(interger)
                                pos= position_setpoint(interger)
                                my_drive.axis0.controller.move_to_pos(pos)
                                actual_time = time.monotonic()
                                t0 = actual_time - start_time
                                time.sleep(adjSpeed)  
I tried using f.seek(0) but it just gave me errors
I appreciate any help
I believe f.seek(0)
will do the trick. Remember to reset any counters, etc that you might be using.
You can use fd.seek(0) if there was no next call.
It works with the csv-module:

import csv
import sys
import time


def csv_cycle(file):
    with open(file) as fd:
        reader = csv.DictReader(fd)
        while True:
            for row in reader:
                yield row
            fd.seek(0)
            fd.readline() # skips the header


file = sys.argv[1]

for row in csv_cycle(file):
    # do something with row
    time.sleep(0.5)
    print(row)
When then for-loop is done, then fd.seek(0) is called. The fileobject goes back to position 0 and the csv.DictReader will use use.
Then you have to skip one line, but don't use the next call on the fd. Otherwise the fileobject is locked for seeking to different positions.
During the creation of DictReader, it reads automatically the first line of the csv-file to get the field names.