在子目录中随机选择x个文件

2024-06-25 23:52:23 发布

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

我需要在一个数据集中随机抽取10个文件(图像),但这个数据集是分层结构的

因此,我需要为每个包含图像的子目录随机保存10个图像。有没有一个简单的方法可以做到这一点,或者我应该手动完成

def getListOfFiles(dirName):
    ### create a list of file and sub directories 
    ### names in the given directory 
    listOfFile = os.listdir(dirName)
    allFiles = list()
    ### Iterate over all the entries
    for entry in listOfFile:

        ### Create full path
        fullPath = os.path.join(dirName, entry)
        ### If entry is a directory then get the list of files in this directory 
        if os.path.isdir(fullPath):
            allFiles = allFiles + getListOfFiles(fullPath)
        else:
            allFiles.append(random.sample(fullPath, 10))
    return allFiles

dirName = 'C:/Users/bla/bla'

### Get the list of all files in directory tree at given path
listOfFiles = getListOfFiles(dirName)

with open("elements.txt", mode='x') as f:
    for elem in listOfFiles:
        f.write(elem + '\n')

Tags: ofthe数据pathin图像osdirectory
1条回答
网友
1楼 · 发布于 2024-06-25 23:52:23

从未知大小的目录列表中获取样本的好方法是使用Reservoir Sampling。使用这种方法,您不必预先运行并列出目录中的所有文件。一个接一个地读,然后取样。它甚至可以在您必须跨多个目录对固定数量的文件进行采样时工作

最好使用基于生成器的目录扫描代码,它一次只选择一个文件,因此您不需要预先使用大量内存来保存所有文件名

顺理成章(注意!未列出的代码!)

import numpy as np
import os

def ResSampleFiles(dirname, N):
    """pick N files from directory"""

    sampled_files = list()
    k = 0
    for item in scandir(dirname):
        if item.is_dir():
            continue
        full_path = os.path.join(dirname, item.name)
        if k < N:
            sampled_files.append(full_path)
        else:
            idx = np.random.randint(0, k+1)
            if (idx < N):
                sampled_files[idx] = full_path
        k += 1

    return sampled_files

相关问题 更多 >