1. 程式人生 > >python 監控文件目錄變化

python 監控文件目錄變化

python os.listdir 監控目錄

使用os.listdir()監控文件目錄:

#!/usr/bin/env python
#-*- coding=utf-8 -*-
#filename: monitor_dir.py
import os
import time
monitor_dir = "/opt/"
now_file = dict([(f,None)for  f in os.listdir(monitor_dir)])
while True:
    new_file = dict([(f,None)for  f in os.listdir(monitor_dir)])
    added = [f for f in new_file if not f in now_file]
    removed = [f for f in now_file if not f in new_file]
    if added:
        print ("Added:",",".join(added))
    if removed:
        print ("Removed:",",".join(removed))
    now_file = new_file


python 監控文件目錄變化