2013-12-11 19 views
0

我想讀取文件,並在文件發生更改(即,對於外部程序)時,打印新的信息。 事情是這樣的:讀取外部文件並等待Python中的更改

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! 

非常感謝。


編輯: 解決辦法:

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

看這個https://github.com/seb-m/pyinotify – Deck

回答

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) 
+0

只有在舊文件上附加了編輯時纔有效。 – M4rtini

+0

文件可能會更改,而不會更改其大小。 – smeso

+0

os.path.getmtime(文件)獲取文件的編輯時間與此相同的原則,不尋求原始文件 – M4rtini

-2

可能做這樣的事情最好的辦法是使用一些工具,操作系統就像inotify的Linux操作系統。 我不知道Windows上是否有類似的東西。

+2

這將是很好,如果人們能解釋他們的理由,而不是默默地往下投票的答案... – smeso

+0

我工作在Fedora。感謝您的快速回答。 – Antonio

+0

不客氣。但下次在發佈之前進行搜索。 – smeso

相關問題