python watchdog 監視資料夾中的檔案變更

安裝套件:
    
pip install watchdog
    

程式碼示範:
    
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import time

class MyHandler(FileSystemEventHandler):
    def on_any_event(self, event):
        print(f"偵測到事件: {event.event_type} - {event.src_path}")

# 設定檔案監視
path = "./"  # 監視當前資料夾
event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)  # recursive=True 包含子資料夾
observer.start()

# 持續執行
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    observer.stop()

observer.join()

    

使用 watchdog 時要建立自己的 handler 類別,並且繼承 FileSystemEventHandler ,在上面的範例程式碼就是 MyHandler 。可以複寫以下幾種方法達成監視的目的:
  • on_created: 檔案或資料夾被建立
  • on_modified: 檔案或資料夾被修改
  • on_deleted: 檔案或資料夾被刪除
  • on_moved: 檔案或資料夾被移動或重新命名
  • on_closed: 檔案被關閉
  • on_closed_no_write: 檔案沒有被寫入就關閉
  • on_opened: 檔案被開啟
  • dispatch:決定事件發生時會被分派到上面的哪個事件中,大多數情況下不需要使用到。
  • on_any_event:上述任何事件都會觸發


文章撰寫中...請稍後...

留言