Python 如何检查文件是否在某个时间间隔内被修改?
我正在尝试自动化一些服务器功能,需要您的帮助。问题是我对Python非常陌生,而且我仅限于Python 2.7.12,无法下载外部模块,如Watchdog。我目前正在Windows上工作,我的程序如下所示:Python 如何检查文件是否在某个时间间隔内被修改?,python,python-2.7,for-loop,Python,Python 2.7,For Loop,我正在尝试自动化一些服务器功能,需要您的帮助。问题是我对Python非常陌生,而且我仅限于Python 2.7.12,无法下载外部模块,如Watchdog。我目前正在Windows上工作,我的程序如下所示: import os, time os.chdir("C:/Users/DummyPath") path_to_watch = "C:/Users/DummyPath" for f in os.listdir(path_to_watch): before = os.stat(f).
import os, time
os.chdir("C:/Users/DummyPath")
path_to_watch = "C:/Users/DummyPath"
for f in os.listdir(path_to_watch):
before = os.stat(f).st_mtime
while True:
time.sleep(3)
for f in os.listdir(path_to_watch):
after = os.stat(f).st_mtime
if after != before and f.endswith(".doc"):
print(time.strftime("%d.%m.%Y %H:%M:%S // Updated: " + f))
before = after
我希望代码在3秒之前和之后比较f中的两个值,但输出总是不同于预期。我该怎么办?在不进行太多检查的情况下,我觉得每个文件都会覆盖
之前的,并且总是只包含os.listdir()中最后一个文件的mtime
值
但实际上,你为什么需要在
之前使用?如果您的目标是查看文件在过去3秒内是否发生了更改,只需检查:
import time
check_interval = 3
while True:
now = time.time()
for f in os.listdir(path_to_watch):
last_mod = os.stat(f).st_mtime
if now - last_mod < check_interval: # file changed in last N seconds
print "File {} changed {} sec. ago".format(f, now - last_mod)
time.sleep(check_interval)
导入时间
检查间隔=3
尽管如此:
now=time.time()
对于os.listdir中的f(路径到监视):
last_mod=os.stat(f).st_mtime
如果现在-last_mod
(我没有测试这段代码,但从概念上讲,这应该是可行的)
此外,由于您提到您在Windows上,请注意以下关于stat
的警告:
注意st_-atime、st_-mtime和
时间属性取决于操作系统和文件
系统。例如,在使用FAT或FAT32文件的Windows系统上
系统中,st_mtime的分辨率为2秒,而st_atime只有1天
决议有关详细信息,请参阅操作系统文档
您需要分别存储所有文件的更新时间,最好是在字典中。尝试以下方法:
import os, time
os.chdir("C:/Users/DummyPath")
path_to_watch = "C:/Users/DummyPath"
time_log = {}
for f in os.listdir(path_to_watch):
time_log[f] = os.stat(f).st_mtime
while True:
time.sleep(3)
for f in os.listdir(path_to_watch):
if f in time_log.keys():
after = os.stat(f).st_mtime
if after != time_log[f] and f.endswith(".doc"):
print(time.strftime("%d.%m.%Y %H:%M:%S // Updated: " + f))
time_log[f] = after
else:
print("New file: "+f)
time_log[f] = os.stat(f).st_mtime
也许您可以给我们当前的结果以及实际期望的结果?您在
时间之前只存储一个,但在可能包含多个文件的目录上迭代。因为每个文件都有不同的mtime,所以它总是检测到更改,因为它会比较不同文件的mtime。另外:它会让您只启动一次,然后再也不会启动,如果有人添加文件会发生什么情况?或者这是不可能的?正确@shevron。然后他需要维护一个列表(一般来说),它基于您的代码,并以类似的方式工作@shevron的方法更好,如果您不需要修改时间,则“更高效”。这种方法可能更好,但@Chris remark很好:如果添加了文件,用户需要做什么。因此,也许维护一个列表是必要的。