-2

I have a Python that is going to read every x seconds a CSV file.

What I do is:

    Open the file, read the info as CSV, loop every entry

This is done in this Python file:

import csv
import time
import datetime


CSV_PLAN = "./XoceKochPlan.csv"
chargePlanFile = open(CSV_PLAN, 'rt')

def loopMe():
    try:
        for eachRow in reader:
            print (eachRow)
    except Exception, ex:
        print ("Error processFileing the Thread" + str(ex))


print ("opening file " + str(CSV_PLAN))
now = datetime.datetime.utcnow().strftime("%a %b %d %H %M %S %Z %Y")
print ("Now " + str(now))
reader = csv.reader(chargePlanFile)

loopMe()

The output is so far so good.

But if I do:

loopMe()
time.sleep(10)
loopMe()

then the file is only printed once!

The question is Why?

What am I missing? What is getting internally consumed, or is the reader just empty after the first loop?

martineau
  • 119,623
  • 25
  • 170
  • 301
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97

2 Answers2

1

In python the file io handler has an internal pointer. After reading the file it will be at the end of the csv file. Ensure you call the chargePlanFile.close() method and reopen the file before calling the loopme() function. Or use the chargePlanFile.seek(0) to reset the position of the internal pointer.

ryanolee
  • 89
  • 4
0

When you start the second loop, your reader is already at the last line. You should reassign the reader. You should do it inside your loopMe function at the beginning.

def loopMe():
    reader = csv.reader(chargePlanFile)
    try:
        for eachRow in reader:
            print (eachRow)
    except Exception, ex:
        print ("Error processFileing the Thread" + str(ex))

If you would keep the same code, just add reader.seek(0) in the first line of loopMe

iFlo
  • 1,442
  • 10
  • 19