Windows环境下,如何在文件夹新增文件/Word文件时自动运行Python脚本?
问题1:如何在文件夹中有文件新增时自动运行Python脚本?
我之前做过不少文件监控相关的需求,给你几个实用的落地方案,从纯Python实现到系统级工具都覆盖了:
方案1:用Python的watchdog库(最推荐)
这是专门做文件系统监控的轻量库,跨平台还灵活,完全用Python就能搞定。步骤如下:
- 先安装依赖:
pip install watchdog - 监控脚本示例:
from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler import subprocess class NewFileTriggerHandler(FileSystemEventHandler): def on_created(self, event): # 排除文件夹创建的事件,只处理文件 if not event.is_directory: print(f"检测到新文件:{event.src_path}") # 替换成你要运行的目标Python脚本路径,还能把新文件路径传过去 subprocess.run(["python", "你的处理脚本路径.py", event.src_path]) if __name__ == "__main__": # 替换成你需要监控的文件夹路径 target_dir = "C:/要监控的文件夹" event_handler = NewFileTriggerHandler() observer = Observer() observer.schedule(event_handler, target_dir, recursive=False) observer.start() try: # 保持脚本后台运行 while True: pass except KeyboardInterrupt: observer.stop() observer.join()
这个脚本会实时监控文件夹,一有新文件就触发你的处理逻辑,还能直接把新文件路径传给处理脚本,非常方便。
方案2:系统级工具(适合不想一直挂Python进程的场景)
Windows:任务计划程序 + 批处理脚本
适合接受一定延迟的场景,比如每隔5分钟检查一次:
- 先写批处理脚本
check_new_files.bat:
@echo off set "watch_dir=C:\要监控的文件夹" set "last_file_list=last_files.txt" set "current_file_list=current_files.txt" # 生成当前文件夹的文件列表 dir /b /a-d "%watch_dir%" > "%current_file_list%" # 对比上次的文件列表,没变化就退出 fc "%last_file_list%" "%current_file_list%" > nul if not errorlevel 1 goto end # 有新文件,运行Python脚本 python "你的处理脚本路径.py" # 更新文件列表,下次对比用 copy "%current_file_list%" "%last_file_list%" > nul :end del "%current_file_list%"
- 打开任务计划程序,创建新任务:触发器选「每隔X分钟」,操作选启动这个批处理脚本即可。
Linux/macOS:inotifywait(实时监控)
安装inotify-tools后,写个shell脚本后台运行:
watch_dir="/path/to/your/dir" inotifywait -m -e create --format "%w%f" "$watch_dir" | while read new_file do # 只处理文件,排除文件夹 if [ -f "$new_file" ]; then python3 /path/to/your/script.py "$new_file" fi done
可以把这个脚本配置成systemd服务,实现开机自启后台运行。
问题2:在Windows操作系统中,如何在特定文件夹新增Word文件时自动运行Python脚本,并在运行后对该Word文件进行处理?
这个需求可以拆成「监控Word文件新增」+「处理Word文件」两部分,我给你一套完整的可落地方案:
步骤1:用watchdog监控+处理Word文件
先安装所需依赖:pip install watchdog python-docx(python-docx用来处理.docx格式的Word文件)
然后写整合了监控和处理的脚本:
from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler from docx import Document import os import win32com.client as win32 # 处理旧版.doc文件需要这个库 class WordFileProcessor(FileSystemEventHandler): def on_created(self, event): if not event.is_directory: file_path = event.src_path # 区分处理.docx和.doc格式 if file_path.lower().endswith(".docx"): print(f"开始处理docx文件:{file_path}") self.process_docx(file_path) elif file_path.lower().endswith(".doc"): print(f"开始处理doc文件:{file_path}") self.process_doc(file_path) def process_docx(self, file_path): # 这里写你的docx处理逻辑,示例:读取内容并添加标记 doc = Document(file_path) # 在文档末尾添加处理标记 doc.add_paragraph("\n--- 此文件已通过Python脚本自动处理 ---") # 可以覆盖原文件,或者存为新文件 doc.save(file_path) # doc.save(f"{os.path.splitext(file_path)[0]}_处理后.docx") print(f"docx文件处理完成:{file_path}") def process_doc(self, file_path): # 处理旧版.doc文件,需要依赖Office的COM接口 word_app = win32.gencache.EnsureDispatch('Word.Application') doc = word_app.Documents.Open(file_path) # 添加处理标记 doc.Content.InsertAfter("\n--- 此文件已通过Python脚本自动处理 ---") doc.Save() doc.Close() word_app.Quit() print(f"doc文件处理完成:{file_path}") if __name__ == "__main__": # 替换成你要监控的文件夹路径 target_dir = "C:/存放Word文件的文件夹" event_handler = WordFileProcessor() observer = Observer() observer.schedule(event_handler, target_dir, recursive=False) observer.start() print(f"已开始监控文件夹:{target_dir}") try: while True: pass except KeyboardInterrupt: observer.stop() observer.join()
步骤2:让脚本在Windows后台持续运行
如果你不想一直开着命令行窗口,可以把脚本做成后台运行的程序:
- 用
pyinstaller打包成无窗口exe:- 先安装:
pip install pyinstaller - 打包命令:
pyinstaller --onefile --windowed 你的脚本名.py,生成的exe在dist文件夹里
- 先安装:
- 设置开机自启:
- 打开任务计划程序,创建新任务:
- 触发器选「登录时」(开机自动启动)
- 操作选「启动程序」,选择刚才生成的exe文件
- 条件里取消勾选「只有在计算机使用交流电源时才启动此任务」(适合笔记本离线使用)
- 打开任务计划程序,创建新任务:
注意事项
- 处理
.doc文件时,需要确保你的Windows系统安装了Microsoft Office,否则COM接口无法调用 - 要给脚本分配监控文件夹的读写权限,避免处理时出现权限报错
内容的提问来源于stack exchange,提问作者O. Schultz




