python --监控文件变化
- import os
- import time
-
- # 文件路径
- file_path = r'D:\code\windows_firewall\conf\back_ip.txt'
-
- # 获取文件的最后修改时间
- current_mtime = os.path.getmtime(file_path)
-
- # 初始化上次修改时间
- previous_mtime = current_mtime
-
- while True:
- # 获取文件的最后修改时间
- current_mtime = os.path.getmtime(file_path)
-
- # 检查文件是否发生变化
- if current_mtime != previous_mtime:
- print("文件发生变化!")
- # 在这里执行文件变化后的操作
- # ...
-
- # 更新上次修改时间
- previous_mtime = current_mtime
-
- # 休眠一段时间后再次检查
- time.sleep(1) # 休眠1秒后再次检查文件变化
-
还有更为精准的监控 可以监控文件夹