使用Python从选定子文件夹复制文件至指定目标子文件夹
实现思路与代码示例
核心逻辑
本质是遍历指定的源子文件夹集合,逐个提取目标文件并复制到指定目录,关键是明确「哪些子文件夹要处理」和「复制规则(仅根目录/递归嵌套)」。
分步实现
1. 准备依赖库
Python自带的shutil(文件操作)和os(路径处理)完全够用,无需额外安装。
2. 定义关键参数
先把要处理的源子文件夹路径列成列表,同时指定目标文件夹:
# 替换成你的实际路径 source_folders = [ "/home/user/docs/sub1", "/home/user/docs/sub3", "/home/user/docs/sub5" ] target_folder = "/home/user/selected_files"
3. 两种复制场景的实现
场景一:仅复制源子文件夹根目录的文件(不包含嵌套子文件夹里的内容)
import os import shutil # 确保目标文件夹存在,不存在则创建 os.makedirs(target_folder, exist_ok=True) for src_dir in source_folders: # 跳过不存在的源文件夹,避免报错 if not os.path.isdir(src_dir): print(f"跳过不存在的目录:{src_dir}") continue # 遍历当前源文件夹下的所有条目 for item in os.scandir(src_dir): # 只处理文件,跳过子文件夹 if item.is_file(): # 构造目标文件路径 target_path = os.path.join(target_folder, item.name) # 复制文件(copy2会保留文件元数据,比如创建时间) shutil.copy2(item.path, target_path) print(f"已复制:{item.name}")
场景二:递归复制源子文件夹下所有嵌套文件(包括子文件夹里的文件)
如果需要把每个源子文件夹里的所有层级文件都复制到目标目录(注意:会扁平化文件结构,同名文件会被覆盖):
import os import shutil os.makedirs(target_folder, exist_ok=True) for src_dir in source_folders: if not os.path.isdir(src_dir): print(f"跳过不存在的目录:{src_dir}") continue # 使用os.walk遍历所有层级的文件 for root, _, files in os.walk(src_dir): for file in files: src_file_path = os.path.join(root, file) target_file_path = os.path.join(target_folder, file) # 处理同名文件:如果目标已存在,自动加后缀(比如file.txt → file_1.txt) counter = 1 while os.path.exists(target_file_path): name, ext = os.path.splitext(file) target_file_path = os.path.join(target_folder, f"{name}_{counter}{ext}") counter += 1 shutil.copy2(src_file_path, target_file_path) print(f"已复制:{src_file_path} → {target_file_path}")
额外优化建议
- 权限处理:可以添加
try-except块捕获PermissionError等异常,避免程序中途崩溃。 - 过滤文件类型:如果只需要复制特定格式的文件(比如
.pdf、.txt),可以在遍历文件时加判断:if file.endswith('.pdf')。 - 批量配置源文件夹:如果源文件夹有规律(比如名字包含特定关键词),可以用
os.listdir遍历父目录,自动筛选符合条件的子文件夹,不用手动写路径列表。
内容的提问来源于stack exchange,提问作者js5656
相关产品推荐
相关产品推荐

