使用python Watchdog获取文件名

2024-06-09 15:45:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试获取一个定期更改的文件名。 我用看门狗来做这件事。在

import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

timestr = time.strftime("%Y.%m.%d-%H.%M.%S")

class MyHandler(FileSystemEventHandler):
    def on_modified(self, event):
        change_log = open('change_log_' + timestr + '.txt', 'aw')
        change_log.write('Time the file changed: ' + timestr + '\n')
        change_log.close()

if __name__ == "__main__":
    event_handler = MyHandler()
    observer = Observer()
    observer.schedule(event_handler, path='.', recursive=False)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except keyboardInterrupt:
        observer.stop()
    observer.join()

出于某种原因,这将在“change_log”文件中打印出大约62行。这不是很有用。 我想做的是打印更改的文件名,或者将其存储在一个变量中以传递给我的另一个模块。在


Tags: fromimporteventlogtime文件名change看门狗