1

I want to read a file and when the file changed (i.e. for a external program), print the new information readed. Something like this:

import sys, os

with open('file.txt', 'r') as f:
    fid = f.fileno()
    r = os.fdopen(fid)
    while True:
        print r.read() 

And when I do:

echo "Hello world!" > file.txt

The python script show:

> Hello world!

Many thanks.


EDITED: The solution:

time = os.path.getmtime('file.txt')
while True:
    if (time <> os.path.getmtime('file.txt')):
        with open('file.txt', 'r') as f:
            info = f.read()
            print "Readed: " + info
        time = os.path.getmtime('file.txt')
Antonio
  • 91
  • 1
  • 7

2 Answers2

1

Get file modified time, read if it increases from the old 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)
M4rtini
  • 13,186
  • 4
  • 35
  • 42
0

Check Python watchdog. Python Watchdog quickstart

watchdog.events.FileModifiedEvent should do the trick.

lipponen
  • 733
  • 1
  • 5
  • 18