如何用Python按CSV清单从多子目录复制指定.png文件?
批量复制分散子目录中的PNG文件方案
以下提供两种实用方法,根据你的技术习惯选择:
方法一:Python脚本(灵活可控)
适合需要自定义逻辑或处理复杂场景的情况,无需额外安装工具(用Python内置模块即可)。
步骤与代码
import os import shutil import csv # 请根据实际情况修改以下参数 CSV_FILE = "你的文件名列表.csv" # 存储文件名的CSV路径 SOURCE_DIR = "images" # 包含子目录的源文件夹 TARGET_DIR = "target_images" # 目标独立文件夹 # 创建目标文件夹(不存在则自动创建) os.makedirs(TARGET_DIR, exist_ok=True) # 读取CSV中的文件名列表(假设文件名在第一列,若在其他列修改索引,如第二列用row[1]) target_files = set() with open(CSV_FILE, 'r', encoding='utf-8') as f: csv_reader = csv.reader(f) for row in csv_reader: if row: # 跳过空行 target_files.add(row[0].strip()) # 遍历源目录所有子文件夹,匹配文件并复制 for root, _, files in os.walk(SOURCE_DIR): for file in files: if file.endswith('.png') and file in target_files: src_path = os.path.join(root, file) dest_path = os.path.join(TARGET_DIR, file) if not os.path.exists(dest_path): shutil.copy2(src_path, dest_path) # copy2保留文件元数据 print(f"复制完成: {file}") else: print(f"已存在,跳过: {file}")
注意事项
- 如果CSV中文件名不带
.png后缀,需在代码里给每个文件名加上:target_files.add(f"{row[0].strip()}.png") - 若CSV编码为GBK(Windows常见),将
encoding='utf-8'改为encoding='gbk'
方法二:命令行工具(无需编程)
适合快速操作,分Windows和Linux/macOS两种环境:
Windows(PowerShell)
- 先将CSV中的文件名列导出为纯文本文件
file_list.txt,每行一个文件名(确保带.png后缀) - 打开PowerShell,切换到工作目录,执行:
$targetDir = "target_images" New-Item -ItemType Directory -Force -Path $targetDir Get-Content .\file_list.txt | ForEach-Object { Get-ChildItem -Path .\images -Filter $_ -Recurse | Copy-Item -Destination $targetDir -Force }
Linux/macOS(Bash)
- 同样导出文件名到
file_list.txt(每行一个) - 打开终端执行:
mkdir -p target_images while read filename; do find ./images -name "$filename" -type f -exec cp {} target_images/ \; done < file_list.txt
注意事项
- 若文件名包含空格,确保
file_list.txt中的文件名完整保留空格 - 命令行方式如果找到多个同名文件,会直接覆盖目标文件夹中的文件,需注意重复文件名问题
内容的提问来源于stack exchange,提问作者eleanorros
相关产品推荐
相关产品推荐

