文件整理是Python自动化里最容易落地的一类任务。下载目录堆积、临时缓存过期、报表按类型归档,本质上都落在四类操作上:路径解析、目录遍历、文件读写、复制移动删除。原文把核心库分成三块:os负责底层文件系统调用和传统路径拼接,pathlib用Path对象处理路径和遍历,shutil承担复制目录树、移动文件、删除非空目录等高级操作。新脚本可以优先用pathlib处理路径,用shutil做复制移动删除,os作为补充。
一、路径处理与目录遍历
字符串拼接路径在Windows上容易遇到分隔符混乱问题,pathlib把路径封装成Path对象,用 / 运算符拼接,并自动适配当前系统。Path对象还提供name、stem、suffix、parent等属性,批量重命名和按扩展名分类时很实用。注意suffix带点号,重命名拼接时要自行处理。
- from pathlib import Path
- current = Path.cwd()
- img_dir = current / 'data' / 'images'
- home = Path.home()
- abs_path = img_dir.resolve()
- p = Path('/home/user/project/report_2025.xlsx')
- print(p.name)
- print(p.stem)
- print(p.suffix)
- print(p.parent)
复制代码
遍历目录可按场景选择接口。iterdir()只列第一层,需要自己用is_dir()、is_file()判断;glob()只匹配当前目录,rglob()递归匹配子目录;rglob('*')会包含目录本身,过滤时要结合is_file()。os.walk返回root、dirs、files三元组,还可以原地修改dirs来剪枝,跳过node_modules、.git、__pycache__等无用目录,减少遍历量。
- from pathlib import Path
- d = Path('./data')
- for item in d.iterdir():
- if item.is_dir():
- print(f'目录: {item}')
- elif item.is_file():
- print(f'文件: {item}')
- for txt in d.glob('*.txt'):
- print(txt)
- for txt in d.rglob('*.txt'):
- print(txt)
- for file in d.rglob('*'):
- if file.is_file():
- print(file)
复制代码- from pathlib import Path
- import os
- for root, dirs, files in os.walk('./data'):
- dirs[:] = [d for d in dirs if d not in ('node_modules', '.git', '__pycache__')]
- for f in files:
- print(Path(root) / f)
复制代码
二、文件增删改移与目录级操作
创建文件前建议先创建父目录,mkdir(parents=True, exist_ok=True)是常用写法。写小文件可用write_text(),循环写入时用open()配合with更合适。encoding='utf-8'要显式指定,避免Windows默认编码与中文内容产生乱码;w模式会覆盖,追加要用a模式。
- from pathlib import Path
- p = Path('./output/result.txt')
- p.parent.mkdir(parents=True, exist_ok=True)
- p.write_text('hello world', encoding='utf-8')
- lines = ['line1', 'line2', 'line3']
- with open(p, 'w', encoding='utf-8') as f:
- for line in lines:
- f.write(line + chr(10))
- with open(p, 'r', encoding='utf-8') as f:
- content = f.read()
复制代码
复制和移动主要用shutil。copy只复制内容,copy2会保留修改时间、访问时间等元数据,归档场景建议用copy2。移动前要确保目标父目录存在,否则会抛FileNotFoundError。删除文件用Path.unlink(),删除空目录用Path.rmdir(),删除非空目录树用shutil.rmtree,后者不经过回收站,执行前应核对路径。
- import shutil
- from pathlib import Path
- src = Path('./downloads/report.pdf')
- dst = Path('./archive/report_backup.pdf')
- shutil.copy2(src, dst)
- dst.parent.mkdir(parents=True, exist_ok=True)
- shutil.move(str(src), str(dst))
- p = Path('./temp/file.txt')
- if p.exists():
- p.unlink()
- d = Path('./empty_dir')
- if d.exists():
- d.rmdir()
复制代码
目录树复制用shutil.copytree,Python 3.8起支持dirs_exist_ok=True,目标目录已存在时不再抛FileExistsError。创建多级目录时parents=True和exist_ok=True两个参数都建议显式写出。
- from pathlib import Path
- import shutil
- out = Path('./output/2025/06/report')
- out.mkdir(parents=True, exist_ok=True)
- shutil.copytree(Path('./data'), Path('./backup_data'), dirs_exist_ok=True)
- p = Path('./temp_data')
- if p.exists():
- shutil.rmtree(p)
复制代码
三、实战脚本一:下载目录按扩展名归档
下面脚本把目标目录中的文件按扩展名移动到对应分类目录。classify()用suffix.lower()统一大小写,避免.JPG和.jpg分成两个目录;目标文件重名时用while循环加数字后缀,防止覆盖已有文件;iterdir()只处理当前层,若要处理整个目录树可改用rglob('*')并判断is_file()。
- import shutil
- from pathlib import Path
- TARGET_DIR = Path('./downloads')
- RULES = {
- 'images': ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'],
- 'documents': ['.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.txt', '.md'],
- 'archives': ['.zip', '.rar', '.7z', '.tar', '.gz'],
- 'installers': ['.exe', '.msi', '.dmg'],
- 'videos': ['.mp4', '.avi', '.mkv', '.mov'],
- }
- def classify(file_path: Path):
- suffix = file_path.suffix.lower()
- for category, exts in RULES.items():
- if suffix in exts:
- return category
- return None
- def organize():
- if not TARGET_DIR.exists():
- print(f'目录不存在: {TARGET_DIR}')
- return
- for item in TARGET_DIR.iterdir():
- if item.is_file() and not item.name.startswith('.'):
- category = classify(item)
- if category is None:
- continue
- dest_dir = TARGET_DIR / category
- dest_dir.mkdir(parents=True, exist_ok=True)
- dest = dest_dir / item.name
- counter = 1
- while dest.exists():
- dest = dest_dir / f'{item.stem}_{counter}{item.suffix}'
- counter += 1
- shutil.move(str(item), str(dest))
- print(f'移动: {item.name} -> {category}/{dest.name}')
- if __name__ == '__main__':
- organize()
复制代码
四、实战脚本二:按修改时间清理过期文件
清理脚本用stat().st_mtime获取修改时间,超过设定天数的文件执行unlink()。删除空目录时要把路径按层级从深到浅排序,key=lambda p: len(p.parts)配合reverse=True可先删子目录再删父目录;rmdir()只删空目录,非空会抛OSError,用try/except兜底。删除类脚本建议先加dry-run或注释掉unlink(),只打印待删文件,确认路径无误后再放开。
- import time
- from pathlib import Path
- CLEAN_DIR = Path('./temp_cache')
- MAX_AGE_DAYS = 30
- CLEAN_EMPTY_DIRS = True
- def clean_files():
- if not CLEAN_DIR.exists():
- print(f'目录不存在: {CLEAN_DIR}')
- return
- now = time.time()
- max_age_seconds = MAX_AGE_DAYS * 24 * 60 * 60
- deleted_count = 0
- for item in CLEAN_DIR.rglob('*'):
- if not item.is_file():
- continue
- mtime = item.stat().st_mtime
- age_seconds = now - mtime
- if age_seconds > max_age_seconds:
- print(f'删除: {item} (已存在 {age_seconds / 3600 / 24:.1f} 天)')
- item.unlink()
- deleted_count += 1
- if CLEAN_EMPTY_DIRS:
- for dirpath in sorted(CLEAN_DIR.rglob('*'), key=lambda p: len(p.parts), reverse=True):
- if dirpath.is_dir():
- try:
- dirpath.rmdir()
- print(f'删除空目录: {dirpath}')
- except OSError:
- pass
- print(f'清理完成,共删除 {deleted_count} 个文件')
- if __name__ == '__main__':
- clean_files()
复制代码
五、高频报错与排查要点
Windows下常见PermissionError: [WinError 32],原因是文件被其他程序占用,比如Excel打开了csv,脚本再删除或移动就会失败。处理顺序是先关闭占用程序,再用Process Explorer查找文件句柄,资源管理器预览导致时刷新窗口。另一个是[WinError 5]拒绝访问,多与只读属性或权限有关,可用os.chmod(p, 0o644)去掉只读后再删除。
路径异常可按现象排查:FileNotFoundError多为路径不存在或父目录未创建;NotADirectoryError是把文件路径当目录用;IsADirectoryError是把目录路径当文件用;FileExistsError是目标已存在,需按业务选择覆盖、跳过或加序号;OSError: [Errno 22] Invalid argument要检查文件名是否含系统不支持的尖括号、冒号、斜杠、竖线、问号、星号等字符;UnicodeEncodeError多与控制台编码有关,可设置PYTHONUTF8=1,或在代码里用sys.stdout.reconfigure(encoding='utf-8')。
遍历时不要边遍历边移动或删除目录结构,否则迭代结果可能失效,导致跳过或重复处理。正确做法是先收集目标列表,再统一处理:files = list(CLEAN_DIR.rglob('*.log')),然后循环移动或删除。
环境方面,先执行python --version确认版本。dirs_exist_ok是Python 3.8加入的参数,旧版本会报TypeError。Windows安装时勾选Add Python to PATH,VSCode中通过Ctrl+Shift+P执行Python: Select Interpreter选择解释器,多版本可用py -3.11指定。脚本打包成exe后工作目录可能变化,路径定位建议用Path(__file__).resolve().parent获取脚本所在目录,而不是依赖Path.cwd()。
- from pathlib import Path
- BASE_DIR = Path(__file__).resolve().parent
- data_dir = BASE_DIR / 'data'
- log_dir = BASE_DIR / 'logs'
复制代码
整体流程可以固化为:先规划分类规则和清理条件,再收集文件列表,接着处理重名与异常,最后打印日志或先dry-run确认。pathlib负责路径与遍历,shutil负责复制移动删除,配合显式编码、重名保护和路径核对,文件自动化脚本的稳定性会明显提高。 |