Python 自动化文件整理与分类脚本实战指南
引言
在日常办公中,文件管理往往耗时且易错。手动处理大量文件既繁琐又容易出错,而 Python 提供了强大的标准库支持,可以高效地实现文件的自动归类、重命名和移动。本文将深入讲解如何构建一个可扩展的文件整理系统,涵盖基础脚本编写、高级规则匹配及定时任务部署。
环境准备
确保已安装 Python 3.x 版本。所需第三方库包括 schedule 用于定时任务。
pip install schedule
基础文件整理
利用 os 和 shutil 模块遍历目录并按扩展名分类。此方法适用于简单的按类型归档场景。
核心代码
import os
import shutil
def organize_by_extension(source_folder, destination_folder):
# 确保目标文件夹存在
if not os.path.exists(destination_folder):
os.makedirs(destination_folder)
for filename in os.listdir(source_folder):
source_path = os.path.join(source_folder, filename)
# 仅处理文件,跳过子目录
if os.path.isfile(source_path):
_, ext = os.path.splitext(filename)
ext = ext.lower().lstrip('.')
# 创建对应扩展名的文件夹
target_dir = os.path.join(destination_folder, ext)
if not os.path.exists(target_dir):
os.makedirs(target_dir)
target_path = os.path.join(target_dir, filename)
try:
shutil.move(source_path, target_path)
print(f"Moved: {filename} -> {ext}/")
except Exception as e:
print(f"Error moving {filename}: {e}")


