ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python--文件系统监控

2021-05-12 23:58:24  阅读:130  来源: 互联网

标签:-% python 文件系统 -- time print path now event


文件系统监控

  • 文件系统监控是利用watchdog监控指定目录/文件的变化,如文件或目录的增删改查都会产生一个event事件信息,每种变化都会产生一个事件信息,且有一个特定的事件类与之对应。然后通过事件处理类来处理对应的事件。

  • watchdog需要从第三方库中下载

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'E:\PycharmProjects\untitled\project01\自动化运维\1.基础运维'
    event_handler = FileEventHandler()
    observer.schedule(event_handler, path, True)      # True表示递归子目录
    print(f'监控目录 {path}')
    # 开启监控
    observer.start()
    # 阻塞,使程序有序执行
    observer.join()

# 输出结果:
# 监控目录 E:\PycharmProjects\untitled\project01\自动化运维\1.基础运维
# 2021-05-12 23:40:58 创建文件 E:\PycharmProjects\untitled\project01\自动化运维\1.基础运维\123.txt
# 2021-05-12 23:41:16 删除文件 E:\PycharmProjects\untitled\project01\自动化运维\1.基础运维\123.txt

标签:-%,python,文件系统,--,time,print,path,now,event
来源: https://blog.csdn.net/CN_LiTianpeng/article/details/116724529

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有