Python,检查文件何时保存

0 投票
1 回答
3129 浏览
提问于 2025-04-18 13:10

我们的目标是每当列表中的某个文件被修改(保存)时,就执行一些操作。

我现在不知道该怎么开始。最终的目标应该是像这样:

files = ['file1.txt', 'file2.txt', 'file3,txt']

if (one of the files in files is modified):
    Print '%s has been modified' % (filename)

1 个回答

1

这段代码会使用一个字典来检查时间,并打印出任何被修改过的文件:

 import os.path, time
files = ['file1.txt', 'file2.txt', 'file3,txt']
changes =  {"file1.txt":os.path.getmtime("file1.txt"),"file2.txt":os.path.getmtime("file2.txt"),"file3.txt":os.path.getmtime("file3.txt")}
while True:
    for f in files:
        if changes.get(f) < os.path.getmtime(f):
            print "File {} has been modified".format(f)
            changes[f] = os.path.getmtime(f)
        else:
            print "No changes, going to sleep."
    time.sleep(10)

撰写回答