
import osimport reimport timeimport shutilfrom watchdog.observers import Observerfrom watchdog.events import FileSystemEventHandler# 配置路径(改为你的下载路径)DOWNLOAD_PATH = r"C:\Users\Admin\Downloads"DEST_PATH_SOCIAL = r"D:\财务归档\社保完税证明"DEST_PATH_PROVIDENT = r"D:\财务归档\公积金凭证"class FinanceFileHandler(FileSystemEventHandler):def on_created(self, event):if event.is_directory:returnfile_path = event.src_pathfilename = os.path.basename(file_path)# 1. 处理社保完税证明 (匹配 document*.pdf)if filename.lower().startswith("document") and filename.endswith(".pdf"):self.move_file(file_path, DEST_PATH_SOCIAL, "社保证明")# 2. 处理公积金凭证 (使用正则匹配:纯16位数字 + .pdf)elif re.match(r'^\d{16}\.pdf$', filename):self.move_file(file_path, DEST_PATH_PROVIDENT, "公积金凭证")def move_file(self, src_path, dest_dir, category):try:if not os.path.exists(dest_dir):os.makedirs(dest_dir)# 加上时间戳,防止文件名重复timestamp = time.strftime("%Y%m%d_%H%M%S")new_name = f"{category}_{timestamp}_{os.path.basename(src_path)}"dest_path = os.path.join(dest_dir, new_name)# 稍微延迟,确保浏览器已完成文件写入time.sleep(1)shutil.move(src_path, dest_path)print(f"【自动化成功】检测到{category},已归档至:{dest_path}")except Exception as e:print(f"【处理失败】{e}")if __name__ == "__main__":event_handler = FinanceFileHandler()observer = Observer()observer.schedule(event_handler, DOWNLOAD_PATH, recursive=False)print(f"财务助手已启动,监控下载文件夹中...")observer.start()try:while True:time.sleep(1)except KeyboardInterrupt:observer.stop()observer.join()
「即下即得」:只需在浏览器点「下载」,之后分类、重命名、归档全由 Python 自动完成。
正则精准命中:用 re.match(r'^\d{16}$', ...) 正则匹配,可精准区分公积金凭证和其他乱码文件,零误读。
减少归档压力:月底审计或查账时,文件夹清清楚楚,再也不用逐个「document(99).pdf」瞎找了。
