如何使用Python匹配文本文件中的名称,将对应子目录复制到目标文件夹
失效原因
shutil.copy()仅支持复制单个文件,无法直接复制包含多个子文件的目录,递归复制目录需要使用shutil.copytree()接口- 原代码没有处理目标路径的层级拼接,需要显式拼接目标子目录路径保证结构和源端一致
修正后可运行代码
import os import shutil def main(): destination = "path/to/destination_folder" source = "path_to_source_folder_containing_subdirectories_each_contains_files" # 读取需要复制的子目录名称列表,过滤空行 with open("list.txt", "r", encoding="utf-8") as lines: dirs_to_copy = set(line.rstrip() for line in lines if line.strip()) for dir_name in dirs_to_copy: source_dir_path = os.path.join(source, dir_name) # 拼接目标路径,保证和源端层级结构完全一致 target_dir_path = os.path.join(destination, dir_name) if os.path.isdir(source_dir_path): print(f"copying {source_dir_path} to {target_dir_path}") # 递归复制目录,dirs_exist_ok=True 表示如果目标目录已存在则覆盖内容,Python 3.8+支持 shutil.copytree(source_dir_path, target_dir_path, dirs_exist_ok=True) if __name__ == "__main__": main()
兼容低版本Python的补充说明
如果使用的Python版本低于3.8,不支持dirs_exist_ok参数,可以在执行复制前先判断目标目录是否存在,存在则调用shutil.rmtree(target_dir_path)删除旧目录后再执行shutil.copytree。
内容的提问来源于stack exchange,提问作者RA FI
相关产品推荐
相关产品推荐

