一文详解如何使用Python实现文件监控自动化系统

 更新时间:2026年01月29日 08:58:04   作者:张大狸  
这篇文章主要介绍了如何使用Python实现文件监控自动化系统,解决日常工作中的文件管理痛点,系统基于Watchdog库实时监控文件夹,支持文件自动分类(按类型/大小/日期)和微信通知提醒,文章详细讲解了核心代码实现,需要的朋友可以参考下

一、为什么需要文件监控自动化?

在日常工作中,你是否经常遇到这样的困扰:

  • 同事发来的文件混杂在下载文件夹里,需要手动整理
  • 重要文件被修改却没能及时察觉
  • 紧急合同上传后,需要反复刷新查看是否到位

传统方式 vs 自动化方案对比​:

方式响应速度准确性持续工作能力
人工检查分钟级依赖注意力8小时/天
Python监控秒级100%​24小时/天

二、核心技术:Watchdog库详解

1. 基础监控实现

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

class MyHandler(FileSystemEventHandler):
    def on_created(self, event):
        print(f'新文件出现: {event.src_path}')
        # 这里添加文件处理逻辑

if __name__ == "__main__":
    path = "C:/监控文件夹"  # 替换为你的监控路径,比如微信文件存储路径,各类下载文件夹等
    event_handler = MyHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

关键参数说明​:

  • recursive=True:监控子文件夹
  • event.src_path:获取文件完整路径
  • on_created:响应文件创建事件(还有on_modified, on_deleted等)

2. 增强功能:文件智能分类

def auto_classify(file_path):
    """根据扩展名自动分类文件"""
    from pathlib import Path
    import shutil
    
    ext_map = {
        '.pdf': '文档',
        '.jpg': '图片',
        '.xlsx': '表格'
    }
    
    file = Path(file_path)
    if file.is_file():
        ext = file.suffix.lower()
        target_dir = Path(file.parent) / ext_map.get(ext, '其他')
        target_dir.mkdir(exist_ok=True)
        shutil.move(str(file), target_dir)
        return target_dir / file.name

分类规则扩展建议​:

  • 按项目名称分类(从文件名提取关键词)
  • 按文件大小分类(大文件单独存放)
  • 按修改日期分类(自动归档旧文件)

三、微信实时通知实现

1. 通过Server酱推送

import requests

def wechat_notify(title, content):
    """发送微信通知"""
    SCKEY = "你的Server酱SCKEY"  # 在https://sct.ftqq.com申请
    url = f"https://sc.ftqq.com/{SCKEY}.send"
    data = {
        "text": title,
        "desp": content
    }
    requests.post(url, data=data)

2. 企业微信机器人通知

def qywx_notify(content):
    """企业微信机器人通知"""
    webhook = "你的企业微信群机器人Webhook地址"
    headers = {'Content-Type': 'application/json'}
    data = {
        "msgtype": "text",
        "text": {
            "content": content,
            "mentioned_mobile_list": ["13800138000"]  # 需要@的人
        }
    }
    requests.post(webhook, headers=headers, json=data)

通知内容优化建议​:

  • 包含文件类型、大小、修改时间
  • 添加快速访问链接(局域网路径)
  • 重要文件变更@特定人员

四、完整实战案例

1. 监控+分类+通知完整代码

import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from pathlib import Path
import shutil
import requests

class SmartFileHandler(FileSystemEventHandler):
    def __init__(self):
        self.ext_map = {
            '.pdf': '文档',
            '.docx': '文档',
            '.xlsx': '表格',
            '.jpg': '图片'
        }
    
    def on_created(self, event):
        file_path = event.src_path
        if Path(file_path).is_file():
            target_path = self.classify_file(file_path)
            self.send_notification(file_path, target_path)
    
    def classify_file(self, file_path):
        """文件自动分类"""
        file = Path(file_path)
        ext = file.suffix.lower()
        target_dir = Path(file.parent) / self.ext_map.get(ext, '其他')
        target_dir.mkdir(exist_ok=True)
        shutil.move(str(file), target_dir)
        return target_dir / file.name
    
    def send_notification(self, origin_path, target_path):
        """发送微信通知"""
        file = Path(origin_path)
        msg = f"📁 新文件提醒\n\n" \
              f"文件名:{file.name}\n" \
              f"类型:{file.suffix}\n" \
              f"大小:{file.stat().st_size/1024:.2f}KB\n" \
              f"存放位置:{target_path}"
        wechat_notify("文件监控提醒", msg)

def main():
    path = "C:/监控文件夹"  # 设置监控路径
    event_handler = SmartFileHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    
    print(f"开始监控文件夹: {path}")
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

if __name__ == "__main__":
    main()

2. 部署与优化建议

部署方式​:

Windows系统:打包为exe后台运行

pyinstaller --onefile --windowed file_monitor.py

Linux系统:配置为systemd服务

sudo nano /etc/systemd/system/filemon.service

性能优化​:

添加文件过滤:只监控特定类型文件

if not file_path.endswith(('.pdf', '.docx')):
    return

设置延迟处理:避免短时间重复触发

last_trigger = 0
def on_created(self, event):
    if time.time() - last_trigger < 5:  # 5秒内不重复处理
        return
    last_trigger = time.time()

五、企业级增强方案

安全增强实现部分源码

def check_virus(file_path):
    """简单的文件安全检查"""
    blacklist = ['.exe', '.bat', '.vbs']
    if Path(file_path).suffix.lower() in blacklist:
        wechat_notify("安全警报", f"发现可疑文件: {file_path}")
        quarantine_file(file_path)  # 隔离可疑文件

以上就是一文详解如何使用Python实现文件监控自动化系统的详细内容,更多关于Python自动监控文件夹的资料请关注脚本之家其它相关文章!

相关文章

  • Python中functools模块函数解析

    Python中functools模块函数解析

    这篇文章主要介绍了Python中functools模块的常用函数解析,分别讲解了functools.cmp_to_key,functools.total_ordering,functools.reduce,functools.partial,functools.update_wrapper和functools.wraps的用法,需要的朋友可以参考下
    2017-03-03
  • pytorch:torch.mm()和torch.matmul()的使用

    pytorch:torch.mm()和torch.matmul()的使用

    今天小编就为大家分享一篇pytorch:torch.mm()和torch.matmul()的使用,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-12-12
  • Python常见字符串操作函数小结【split()、join()、strip()】

    Python常见字符串操作函数小结【split()、join()、strip()】

    这篇文章主要介绍了Python常见字符串操作函数,结合实例形式总结分析了split()、join()及strip()的常见使用技巧与注意事项,需要的朋友可以参考下
    2018-02-02
  • python flask安装和命令详解

    python flask安装和命令详解

    Flask是使用Python编写的Web微框架,这篇文章主要介绍了python flask安装和命令,需要的朋友可以参考下
    2019-04-04
  • MySQL Prepared语句的具体使用

    MySQL Prepared语句的具体使用

    本文主要介绍了MySQL Prepared语句的具体使用,可以利用prepared语句来避免重复解析SQL的开销,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-09-09
  • 一文搞懂霍夫曼树原理及C++/Python/Java实战实现

    一文搞懂霍夫曼树原理及C++/Python/Java实战实现

    霍夫曼树是一种用于数据压缩的树形结构,通过构建具有最小带权路径长度的二叉树,实现高效的数据编码,这篇文章主要介绍了霍夫曼树原理及C++/Python/Java实战实现的相关资料,需要的朋友可以参考下
    2025-11-11
  • 使用python制作一款文件粉碎工具

    使用python制作一款文件粉碎工具

    这篇文章主要为大家详细介绍了如何使用python制作一款文件粉碎工具,能够有效粉碎密码文件和机密Excel表格等,感兴趣的小伙伴可以了解一下
    2025-08-08
  • Python使用ctypes调用Windows API清空回收站

    Python使用ctypes调用Windows API清空回收站

    很多朋友刚接触 Windows 编程时,总觉得调用系统底层 API 是一件很高深、非常复杂的事情,感到很害怕,本文就以实现 Windows 上的 清空回收站功能为例,从零开始详解 Python 如何通过 ctypes 库跟 Windows API 进行交互调用,需要的朋友可以参考下
    2026-04-04
  • Python 复平面绘图实例

    Python 复平面绘图实例

    今天小编就为大家分享一篇Python 复平面绘图实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-11-11
  • Python实现打印九九乘法表的不同方法总结

    Python实现打印九九乘法表的不同方法总结

    这篇文章主要为大家介绍了Python实现打印九九乘法表的几种不同方法,文中的示例代码讲解详细,简洁易懂,感兴趣的小伙伴可以跟随小编一起学习一下
    2022-11-11

最新评论