通过子目录循环到示例文件

2024-10-01 15:37:28 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码从dir1中随机选择一个文件样本(在本例中为50),并将它们复制到同名的新文件夹中。在

但是,我有数百个文件夹,我需要从中取样(并复制到一个同名的新文件夹)。在

如何调整代码的第一部分,使我可以遍历所有子目录,并将示例移到同名的新文件夹中。(因此sub dir1的样本去dir1,sub dir2的样本去dir2等)

import os 
import shutil 
import random 
from shutil import copyfile

sourcedir = '/home/mrman/dataset-python/train/1/'
newdir  = '/home/mrman/dataset-python/sub-train/1'


filenames = random.sample(os.listdir(sourcedir), 50)
for i in filenames:
    shutil.copy2(sourcedir + i, newdir)

Tags: 代码import文件夹homeostrainrandomdataset
2条回答

您希望使用os.walk。查看documentation

运行以下命令以了解它的工作原理,并阅读文档以了解如何将其用于解决方案。最终,您将从您提供的路径向下遍历整个目录结构,每次迭代都将给出您所在的当前路径、该级别的所有目录和所有文件。在

另外,假设您要对某个特定的完整路径执行操作,然后确保在创建路径时使用os.path.join。在

your_path = "/some/path/you/want"
for path, dirs, files in os.walk(your_path):
    print(path)
    print(dirs)
    print(files)

解决方案比预期的简单(感谢@idjaw for the tip):

import os, sys
import shutil
import random
from shutil import copyfile

#folder which contains the sub directories
source_dir = '/home/mrman/dataset-python/train/'

#list sub directories 
for root, dirs, files in os.walk(source_dir):

#iterate through them
    for i in dirs: 

        #create a new folder with the name of the iterated sub dir
        path = '/home/mrman/dataset-python/sub-train/' + "%s/" % i
        os.makedirs(path)

        #take random sample, here 3 files per sub dir
        filenames = random.sample(os.listdir('/home/mrman/dataset-python/train/' + "%s/" % i ), 3)

        #copy the files to the new destination
        for j in filenames:
            shutil.copy2('/home/mrman/dataset-python/train/' + "%s/" % i  + j, path)

相关问题 更多 >

    热门问题