读取外部文件并等待Python中的更改

时间:2013-12-11 12:05:21

标签: python file-io

我想读取文件,当文件发生变化时(即对于外部程序),打印已加入的新信息。 像这样:

import sys, os

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

当我这样做时:

echo "Hello world!" > file.txt

python脚本显示:

> Hello world!

非常感谢。


EDITED: 解决方案:

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')

2 个答案:

答案 0 :(得分:1)

获取文件修改时间,读取是否从旧时间开始增加。

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)

答案 1 :(得分:0)

检查Python看门狗。 Python Watchdog quickstart

watchdog.events.FileModifiedEvent应该可以解决问题。