抓取修改后的文件python的名称

问题描述 投票:0回答:1

在一个脚本中是一个观察者算法,我从这里改编:https://www.michaelcho.me/article/using-pythons-watchdog-to-monitor-changes-to-a-directory

我的目标是添加几行来获取任何已修改文件的名称,以便我可以使用if语句检查某个文件,例如:

if [modified file name] == "my_file":
    print("do something")

我没有看门狗或文件观看的经验,所以我很难找到答案。我如何收到修改后的文件名?

python watchdog file-watcher python-watchdog
1个回答
1
投票

看门狗类的当前设置是非常无用的,因为它只是打印...它不返回任何东西。

让我提供一个不同的方法:

以下内容将为您提供过去12小时内修改过的文件列表:

result = [os.path.join(root,f) for root, subfolder, files in os.walk(my_dir) 
            for f in files 
            if dt.datetime.fromtimestamp(os.path.getmtime(os.path.join(root,f))) > 
            dt.datetime.now() - dt.timedelta(hours=12)]

除了固定增量小时,您可以保存last_search_time并在后续搜索中使用它。

然后,您可以搜索结果以查看它是否包含您的文件:

if my_file in result:
    print("Sky is falling. Take cover.")
© www.soinside.com 2019 - 2024. All rights reserved.