代码之家  ›  专栏  ›  技术社区  ›  ah bon

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

  •  0
  • ah bon  · 技术社区  · 6 年前

    在文件路径d:/src下,我有images文件夹及其子文件夹,它们具有以下常规结构:

    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。我怎么能用蟒蛇做呢?谢谢。

    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 回复  |  直到 6 年前
        1
  •  1
  •   grapes    6 年前

    试试这个

    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')
    
        2
  •  1
  •   DollarAkshay    6 年前

    假设你有两个层次的嵌套

    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 . 如果是,那么将该目录中的所有文件复制到目标文件夹。

        3
  •  1
  •   glhrsh    6 年前

    这是一个简短的脚本,应该完成这项工作…

    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))