从指定子文件夹批量复制JPG文件失败,求解决方案
批量复制指定子文件夹中的JPG文件
问题场景
文件结构如下:
Main_Directory SubDirectory1 targetfolder file1.gz file1.jpg unwantedfolder file1.gz file1.jpg SubDirectory2 targetfolder file2.gz file2.jpg unwantedfolder file2.gz file2.jpg SubDirectory3 targetfolder file3.gz file3.jpg unwantedfolder file1.gz file1.jpg
需要将所有targetfolder下的JPG文件复制到/depot/only_pics/目录,但之前尝试的命令和Python代码都未达到预期效果。
尝试过的错误方法
错误的find+cp命令
find -name "*/targetfolder/..qz" | xargs cp --parents -t /depot/only_pics/
问题点:
- 文件名后缀写错成
..qz,应为.jpg -name参数仅匹配文件名,无法精准定位targetfolder下的文件,用-path更合适--parents会保留原路径层级,不符合“直接复制到新文件夹”的需求
错误的Python代码
import os from os.path import join, isfile BASE_PATH = '/Main_Directory/' SUBFOLDER = 'targetfolder' for folder, subfolders, *_ in os.walk(BASE_PATH): if SUBFOLDER in subfolders: full_path = join(BASE_PATH, folder, SUBFOLDER) files = [f for f in os.listdir(full_path) if isfile(join(full_path, f)) and f.lower().endswith(('.jpg', '.jpg'))] for f in files: file_path = join(full_path, f) print (f'Copy {f} /depot/only_pics/')
问题点:
full_path拼接错误:os.walk返回的folder已是BASE_PATH下的子目录,重复拼接会导致路径无效endswith里重复写了.jpg,属于冗余代码- 仅打印复制提示,未执行实际复制操作
正确解决方案
方法一:命令行(find+cp)
直接用find匹配所有targetfolder下的JPG文件,再复制到目标目录:
find Main_Directory -path "*/targetfolder/*.jpg" -type f -exec cp {} /depot/only_pics/ \;
如果需要匹配大小写不同的JPG文件(比如.JPG),可改用-iname参数:
find Main_Directory -path "*/targetfolder/*" -type f -iname "*.jpg" -exec cp {} /depot/only_pics/ \;
方法二:Python代码(使用shutil完成复制)
修正路径问题并添加实际复制逻辑:
import os import shutil from os.path import join, isfile BASE_PATH = '/Main_Directory/' TARGET_FOLDER = 'targetfolder' DEST_PATH = '/depot/only_pics/' # 确保目标目录存在,不存在则创建 os.makedirs(DEST_PATH, exist_ok=True) for root, dirs, files in os.walk(BASE_PATH): # 检查当前目录下是否包含targetfolder if TARGET_FOLDER in dirs: target_path = join(root, TARGET_FOLDER) # 遍历targetfolder下的所有文件 for file in os.listdir(target_path): file_full_path = join(target_path, file) # 仅处理JPG文件(不区分大小写) if isfile(file_full_path) and file.lower().endswith('.jpg'): # 执行复制操作 shutil.copy(file_full_path, DEST_PATH) print(f'已复制:{file}')
内容的提问来源于stack exchange,提问作者Devender Arora
相关产品推荐
相关产品推荐

