3

I have a python script which needs to read a text file, do some commands, wait until the text file receives new information, and then do the whole process again. Is there a way to make the python script do such a thing (stay idle until some new information is appended to the text file)?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    Does this answer your question? [How do I watch a file for changes?](https://stackoverflow.com/questions/182197/how-do-i-watch-a-file-for-changes) – 9769953 Oct 18 '21 at 13:31

2 Answers2

3

You could read the last modified time to check if your file has been modified every x time.

import os
import time
fileName = 'test'
originalTime = os.path.getmtime(fileName)

while(True):
    if(os.path.getmtime(fileName) > originalTime):
        with open(fileName, 'r') as f:
            print "\n" + f.read(),
        originalTime = os.path.getmtime(fileName)
    time.sleep(0.1)
xBurnsed
  • 410
  • 4
  • 12
3
a = os.path.getmtime(path)
while (a == os.path.getmtime(path)):
    time.sleep(0.5) ## so this doesn't kill your computer

and then that loop will run until the file date/time modified changes within half a second accuracy (if we are talking ideal case). You can lower that time, I put a pretty generous time in there.

James E
  • 186
  • 9