Python Forum
Continuously iterating through a csv file - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Continuously iterating through a csv file (/thread-24658.html)



Continuously iterating through a csv file - ExplodingCoyote - Feb-25-2020

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


RE: Continuously iterating through a csv file - Larz60+ - Feb-26-2020

I believe f.seek(0)
will do the trick. Remember to reset any counters, etc that you might be using.


RE: Continuously iterating through a csv file - DeaD_EyE - Feb-26-2020

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.