监视文件夹中的文件

Monitoring a folder for files

你能告诉我如何实现检测文件夹中具有相同扩展名的两个文件的可能性吗?

也就是我需要一个folder会被跟踪,一旦two files后缀.txt出现在这个folder中,那么就是有必要识别比同一文件夹中其他所有人创建得更早的文件(即,它将是最旧的)并在屏幕上显示其 name,例如,或任何其他 functions.

我发现这种方法可以跟踪 folder...我在上面描述过。

#!/usr/bin/env python3

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


class EventHandler(FileSystemEventHandler):
    def on_created(self, event):
        result = (event.event_type, event.src_path)
        print(result)


if __name__ == "__main__":

    path = r"/root/test/"
    event_handler = EventHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

根据您的脚本:

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


class EventHandler(FileSystemEventHandler):

    @staticmethod
    def on_created(event):
        action, path = (event.event_type, event.src_path)
        if not "." in path.split(os.sep)[-1]:
            return
        path = ".".join(path.split("."))
        extension = path.split(".")[-1]
        dirname = os.path.dirname(path)

        files = os.listdir(dirname)
        same_ext_files = [os.path.join(dirname, f) for f in files if f.endswith("." + extension)]
        creation_date = [os.path.getmtime(f) for f in same_ext_files]

        print(f"{action = }")
        print(f"{path = }")
        print(f"{extension = }")
        print(f"{dirname = }")
        print(f"{files = }")
        print(f"{same_ext_files = }")
        print(f"{creation_date = }")


if __name__ == "__main__":

    path = os.path.join("/root", "test/")
    if not os.path.isdir(path):
        raise FileNotFoundError
    observer = Observer()
    observer.schedule(EventHandler(), path, recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

正在创建文件 Fichier texte (2).txt:

python test.py 
action = 'created'
path = '/home/vince/Bureau/Whosebug/Fichier texte (2).txt'
extension = 'txt'
dirname = '/home/vince/Bureau/Whosebug'
files = ['Fichier texte (2).txt', 'Fichier texte (1).txt', 'Fichier texte.txt', 'test.py']
same_ext_files = ['/home/vince/Bureau/Whosebug/Fichier texte (2).txt', '/home/vince/Bureau/Whosebug/Fichier texte (1).txt', '/home/vince/Bureau/Whosebug/Fichier texte.txt']
creation_date = [1638378453.7645514, 1638378430.8448474, 1638378409.4784563]

您现在有两个列表:same_ext_filescreation_date 可以通过管道传送到您想要的任何内容。

code fixed to working