从Python中的多个特定子文件夹复制文件

时间:2019-01-14 16:29:47

标签: python operating-system glob shutil

在文件路径D:/ src下,我有图像文件夹及其子文件夹,这些文件夹的常规结构如下:

Folder A
- Subfolder a
- Subfolder b
- Subfolder c
Folder B
- Subfolder a
- Subfolder b
- Subfolder c
- Subfolder d
Folder C
- Subfolder a
- Subfolder b
- Subfolder c
...

我想将子文件夹b中的所有.jpg文件从文件夹A,B,C等复制到D:/ dst中的新文件夹子文件夹b中。如何在Python中完成?谢谢。

Subfolder b
-xxx.jpg
-xyx.jpg
-yxz.jpg
...

以下是我从以下链接中发现的内容可能会有所帮助:

Copy certain files from one folder to another using python

import os;
import shutil;
import glob;

source="C:/Users/X/Pictures/test/Z.jpg"
dest="C:/Users/Public/Image"

    if os.path.exists(dest):
    print("this folder exit in this dir")
else:
    dir = os.mkdir(dest)

for file in glob._iglob(os.path.join(source),""):
    shutil.copy(file,dest)
    print("done")

3 个答案:

答案 0 :(得分:1)

尝试一下

import os
from os.path import join, isfile

BASE_PATH = 'd:/test'
SUBFOLDER = 'Subfolder b'

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', '.jpeg'))]
        for f in files:
            file_path = join(full_path, f)
            print (f'Copy {f} somewehere')

答案 1 :(得分:1)

假设您有2个嵌套级别

root_dir = './data'
dest_dir = './new_location'
os.listdir(root_dir)

for folder in os.listdir(root_dir):
    folder_path = os.path.join(root_dir, folder)
    if os.path.isdir(folder_path):
        for subfolder in os.listdir(folder_path):
            if subfolder == 'Subfolder B':
                subfolder_path = os.path.join(root_dir, folder, subfolder)
                print(subfolder_path)
                for filename in os.listdir(subfolder_path):
                    file_path = os.path.join(root_dir, folder, subfolder, filename)
                    dest_path = os.path.join(dest_dir, filename)
                    shutil.copy(file_path, dest_path)
                    print("Copied ", file_path, "to", dest_path)

您只需要2个for循环,就可以在内部for循环中检查文件夹名称是否与Subfolder B相匹配。如果确实如此,则将该目录内的所有文件复制到目标文件夹。

答案 2 :(得分:1)

这是一个应该完成工作的简短脚本...

import os

# list all the directories in current directory
dirs = [x[0] for x in os.walk("D:/src")]

for d in dirs:
    ## list all files in A/b/*, B/b/*, C/b/*...
    files_to_copy = os.listdir(os.path.join(d, "b"))  
    for f in files_to_copy:
        if f.endswith(".jpg"):  ## copy the relevant files to dest
            shutil.copy(os.path.join(d, "b", f), os.path.join(dest, f))