我想在程序中读取一个文本文件。但是我只想在更改文本文件时才读取该文件。
如果文本文件未更改,那么我不想再次阅读。我尝试了一些操作,但是每3秒钟会读取一次文本文件。
def load():
f = open('input.txt', 'r')
file = f.read()
f.close()
print(file)
file = int(file)
print file
Timer(3,load).start()
load()
import os
filename = "input.txt"
obj = os.stat(filename)
print("modified time: {}".format(obj.st_mtime))
您可以使用内置的Python库来实现相同的效果。
基于现有代码:
import time
import os.path
mod_time = time.ctime(os.path.getmtime('input.txt'))
def load():
global mod_time
new_mtime = time.ctime(os.path.getmtime('input.txt'))
if new_mtime != mod_time:
mod_time = new_mtime
f = open('input.txt', 'r')
file = f.read()
f.close()
print(file)
file = int(file)
print file
Timer(3,load).start()
load()
[如果您注意到,mod_time
最终会跟踪您要读取的input.txt
文件的更改修改时间。