python - 随机选择子目录中的 x 个文件

标签 python random dataset subdirectory

我需要在数据集中随机抽取 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')

最佳答案

从未知大小的目录列表中采样的好方法是使用 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

关于python - 随机选择子目录中的 x 个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60298439/

相关文章:

python - 将元组列表映射到新列

python - 是什么导致这些 Int64 列引发 TypeError?

Python 3 错误 - TypeError : input expected at most 1 arguments, 得到 3

java - 使 Math.Random 循环,直到达到特定数字

java - 如何从Java文件中读取随机行

r - 从程序加载数据

python - 3D 花式箭头补丁

javascript - 如果他们得到某个字符串,我该如何重定向用户

hadoop - 处理千兆字节的数据

python - python列表类型转换