简体   繁体   English

如何将特定文件从子文件夹复制到python中的新文件夹?

[英]How to copy specific files from the sub-folders to a new folder in python?

I have a folder with several sub-folders, each containing the same number of files (here it is 7).我有一个包含多个子文件夹的文件夹,每个子文件夹包含相同数量的文件(这里是 7 个)。 The code that I use at the present copies all the files from the different sub-folders within a main folder, to another new folder.我目前使用的代码将主文件夹内不同子文件夹中的所有文件复制到另一个新文件夹。

import os
import shutil

src = r'C:\Users\datasets\test\0'
dest = r'C:\Users\datasets\data_new\test\0'

for path, subdirs, files in os.walk(src):
    for name in files:
        filename = os.path.join(path, name)
        shutil.copy2(filename, dest)

I need to modify the code in a way to copy only the last image (ie the 7th image in this case) from each sub-folder (windows file arrangement) to a new folder.我需要以某种方式修改代码,以便仅将每个子文件夹(Windows 文件排列)中的最后一个图像(即本例中的第 7 个图像)复制到新文件夹中。

This should do it for you.这应该为你做。

import os
import shutil
from glob import glob

src = r'C:\temp\datasets\test\0'
dest = r'C:\temp\datasets\data_new\test\0'

for base, dirs, _ in os.walk(src):
    for path in dirs:
        files = sorted(glob(os.path.join(base, path, '*')))
        if len(files) == 0:
            continue
        file = files[-1]
        filename = os.path.join(path, file)
        shutil.copyfile(filename, dest)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何根据文件夹名称将文件从一个带有子文件夹的目录复制到另一个带有子文件夹的目录? - How do I copy files from one directory with sub-folders to another directory with sub-folders based on folder name? 如何将特定文件与子文件夹分开? - How to separate specific files from sub-folders? 如何使用 Python 将子文件夹和文件复制到新文件夹中 - How to Copy Sub Folders and files into New folder using Python 如何在包含许多子文件夹和文件的python文件夹中检索某些文件 - How to retrieve certain files inside a folder containing many sub-folders and files python 如何将多个子文件夹中的图片复制到一个普通文件夹中并重命名? - How to copy images from multiple sub-folders to a common folder and rename them? 如何编译位于带有子文件夹的文件夹中的 Python 软件 - How to compile my Python software that's in a folder with sub-folders 如何打印文件夹/子文件夹并从中导入文件? - How can I print folder/sub-folders and import files from them? 如何让Python查看子文件夹? - How to get Python to look at Sub-Folders? 将批处理图像文件从子文件夹复制到父文件夹 - Copying batch image files from sub-folders to parent folders 如何在不指定子文件夹名称的情况下自动合并来自多个子文件夹的多个 CSV? - How to automatically merge multiple CSVs from multiple sub-folders, without specifying sub-folder name?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM