使用shutil.move移动文件时如何跳过源目录与目标目录一致的场景
批量移动文件同目录报错修复方案
核心逻辑
- 调用
os.path.dirname()提取源文件的所在目录,排除文件名干扰 - 用
os.path.normpath()统一规范化源目录和目标目录的路径格式,解决路径末尾带/不带斜杠、不同系统路径分隔符差异导致的判断失效问题 - 两者路径一致时直接跳过移动操作,避免报错
修复后代码
import os import shutil def move_files(file_list, destination): # 提前规范化目标目录,减少循环内重复计算 normalized_dest = os.path.normpath(destination) for source_file in file_list: # 提取并规范化源文件所在目录 source_dir = os.path.normpath(os.path.dirname(source_file)) # 目录相同跳过移动 if source_dir == normalized_dest: continue shutil.move(source_file, destination)
可选优化(Python 3.4+ 支持pathlib)
用面向对象的路径处理方式代码更简洁,自动处理路径规范化问题:
from pathlib import Path import shutil def move_files(file_list, destination): dest_path = Path(destination).resolve() for source_file in file_list: source_path = Path(source_file) if source_path.parent.resolve() == dest_path: continue shutil.move(source_path, dest_path)
内容的提问来源于stack exchange,提问作者Spatial Digger
相关产品推荐
相关产品推荐

