2020-05-06#python#watchdog監控目錄文件變化

1、監控指定目錄


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

class FileEventHandler(FileSystemEventHandler):
    def __init__(self):
        FileSystemEventHandler.__init__(self)

    def on_moved(self,event):
        now = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
        if event.is_directory:
            print(f"{ now } 文件夾由 { event.src_path } 移動至 { event.dest_path }")
        else:
            print(f"{ now } 文件由 { event.src_path } 移動至 { event.dest_path }")

    def on_created(self,event):
        now = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
        if event.is_directory:
            print(f"{ now } 文件夾由 { event.src_path } 創建")
        else:
            print(f"{ now } 文件由 { event.src_path } 創建")

    def on_deleted(self,event):
        now = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
        if event.is_directory:
            print(f"{ now } 文件夾 { event.src_path } 刪除")
        else:
            print(f"{ now } 文件 { event.src_path } 刪除")

    def on_modified(self,event):
        now = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
        if event.is_directory:
            print(f"{ now } 文件夾 { event.src_path } 修改")
        else:
            print(f"{ now } 文件 { event.src_path } 修改")

if __name__ == "__main__":
    observer = Observer()
    path = r"d:/test/"
    event_handler = FileEventHandler()
    observer.schedule(event_handler,path,True)
    print(f"監控目錄 { path }")
    observer.start()
    observer.join()

2、監控指定目錄內指定的格式文檔

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

class FileEventHandler(FileSystemEventHandler):
    def __init__(self,control):
        FileSystemEventHandler.__init__(self)
        self.control = control


    def on_moved(self,event):
        now = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
        if event.src_path.endswith(self.control):
            print(f"{ now } 文件由 { event.src_path } 移動至 { event.dest_path }")

    def on_created(self,event):
        now = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
        if event.src_path.endswith(self.control):
            print(f"{ now } 文件由 { event.src_path } 創建")

    def on_deleted(self,event):
        now = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
        if event.src_path.endswith(self.control):
            print(f"{ now } 文件 { event.src_path } 刪除")

    def on_modified(self,event):
        now = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
        if event.src_path.endswith(self.control):
            print(f"{ now } 文件 { event.src_path } 修改")

if __name__ == "__main__":
    observer = Observer()
    path = r"d:/test/"
    event_handler = FileEventHandler('.docx')
    observer.schedule(event_handler,path,True)
    print(f"監控目錄 { path }")
    observer.start()
    observer.join()
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。