Python如何修改按名匹配复制文件的脚本 实现文件夹复制功能
支持文件/文件夹混合复制移动的脚本调整方案
原有脚本局限
原有脚本仅调用shutil.copy()方法,该方法仅支持单文件复制,无法识别并处理目录类型条目,且缺少路径存在性判断、目标目录自动创建等容错逻辑,运行时容易报错中断。
原有代码如下:
#If the string matches a file name move it to a new directory dst = r"xxx" with open('Names.txt') as my_file: for filename in my_file: src = os.path.join(r"V:\DATABASES\0 Suspension\Suspensia Pictures") # .strip() to avoid un-wanted white spaces shutil.copy(os.path.join(src, filename.strip()), os.path.join(dst, filename.strip()))
核心调整逻辑
要同时支持文件和文件夹的复制/移动,只需要在操作前先判断源路径的类型,调用对应操作方法即可:
- 匹配到的条目是文件时:使用
shutil.copy2()(保留文件创建时间、修改时间等元数据,也可按需替换为shutil.copy())做复制,使用shutil.move()做移动 - 匹配到的条目是文件夹时:使用
shutil.copytree()递归复制整个文件夹下的所有内容,使用shutil.move()做移动 - 补充必要容错逻辑:提前创建目标目录、跳过空行、判断源路径是否存在、处理目标路径已有同名文件夹的场景,避免脚本中断。
修改后可直接运行的代码
复制场景(文件+文件夹通用)
import os import shutil # 路径配置 src_root = r"V:\DATABASES\0 Suspension\Suspensia Pictures" dst_root = r"xxx" # 替换为实际目标目录路径 # 递归创建目标目录,已存在时不报错 os.makedirs(dst_root, exist_ok=True) with open('Names.txt', 'r', encoding='utf-8') as f: for name_entry in f: target_name = name_entry.strip() # 跳过Names.txt里的空行 if not target_name: continue src_full_path = os.path.join(src_root, target_name) dst_full_path = os.path.join(dst_root, target_name) # 源路径不存在时跳过,打印提示 if not os.path.exists(src_full_path): print(f"未找到对应条目,跳过:{target_name}") continue # 按路径类型选择操作方法 if os.path.isfile(src_full_path): shutil.copy2(src_full_path, dst_full_path) print(f"复制文件完成:{target_name}") elif os.path.isdir(src_full_path): # dirs_exist_ok=True 允许目标位置有同名文件夹,自动合并内容覆盖重名文件(Python3.8+支持) shutil.copytree(src_full_path, dst_full_path, dirs_exist_ok=True) print(f"复制文件夹完成:{target_name}")
移动场景(文件+文件夹通用)
如果需要执行移动而非复制,只需要把路径类型判断分支里的操作替换为shutil.move()即可,不需要区分文件和文件夹写不同方法,shutil.move()本身对文件和文件夹都兼容:
# 替换上述代码中路径判断分支的内容即可 if os.path.isfile(src_full_path) or os.path.isdir(src_full_path): shutil.move(src_full_path, dst_full_path) print(f"移动完成:{target_name}")
注意事项
- 如果使用的Python版本低于3.8,
shutil.copytree()不支持dirs_exist_ok参数,需要提前判断目标路径下是否存在同名文件夹,存在的话先删除再执行复制,或者自定义递归复制逻辑 - 读取Names.txt时建议指定文件编码,避免中文名称乱码导致匹配失败
- 首次运行时建议先把目标路径改成测试目录,确认匹配逻辑正确后再执行正式操作,避免误覆盖文件。
内容的提问来源于stack exchange,提问作者Eddiex045
相关产品推荐
相关产品推荐

