1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python入門 第13章】ファイル監視ツールを作ろう📂自動で動くPythonアプリ🐍✨

Last updated at Posted at 2025-08-10

【Python入門 第13章】ファイル監視ツールを作ろう📂自動で動くPythonアプリ🐍✨

こんにちは、 PythonTimesの蛇ノ目いろは です🌿
今回は「フォルダの中の変化をリアルタイムで検知」する、
ファイル監視ツール をPythonで作ってみるよっ!


🧭 こんなことに使えるよ!

  • ファイルが追加されたら自動で処理
  • ログファイルの変化を検知
  • 特定フォルダの更新をリアルタイム通知
    …などなど、 業務効率化の定番ツール だよ📂

🧰 使うライブラリ:watchdog

pip install watchdog

🛠️ 最小構成の監視コード

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

class MyHandler(FileSystemEventHandler):
    def on_modified(self, event):
        print(f"変更されました:{event.src_path}")

    def on_created(self, event):
        print(f"作成されました:{event.src_path}")

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

    print("監視中... Ctrl+Cで終了")

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

🔍 ポイント解説

  • on_created:新しいファイルやフォルダができたとき
  • on_modified:既存のファイルが変更されたとき
  • observer.schedule():どのパスをどう監視するか設定
  • recursive=False :サブフォルダを含めるなら True

📁 監視対象フォルダを用意しよう

./watch_folder というフォルダをあらかじめ作っておこう!

mkdir watch_folder

🔔 応用:特定ファイルだけ反応したいとき

def on_created(self, event):
    if event.src_path.endswith(".csv"):
        print(f"CSVファイル作成検知:{event.src_path}")

✍️ PEP8的なポイント

  • クラス名は MyHandler のように PascalCase
  • メソッドや変数名は snake_case - 定数(監視フォルダなど)は WATCH_PATH = "./watch_folder" のように大文字で書くと明確!

📌 まとめ

  • watchdog を使えば フォルダの変化をリアルタイム検知 できる!
  • on_created , on_modified で柔軟に対応可能✨
  • 自動処理や通知連携など、 業務効率化に直結
  • コードも PEP8スタイル でわかりやすく🐍

次回は、
「第14章:スケジューラや定時処理」 をお届け予定⏰
「毎日9時に実行」「1時間ごとに監視」など、 定時実行の仕組み を紹介するよ!

フォローしてくれたらうれしいな🐍📂

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?