从文件夹中提取随机文件进行采样

Pulling random files out of a folder for sampling

我需要一种方法来随机提取文件夹中 10% 的文件,以便在每 "run." 之后进行抽样幸运的是,我当前的文件是按数字顺序编号的。所以我目前的方法是列出文件名,解析数字部分,提取最大值和最小值,计算文件数并乘以 .1,然后使用 random.sample 得到一个 "random [10%] sample." 我也写这些名称为 .txt 然后使用 shutil.copy 移动实际文件。

显然,如果我有异常值,即如果我有一个文件 345.txt 以及来自 513.txt - 678.txt 的其他文件,这将不起作用。我想知道是否有一种直接的方法可以简单地从文件夹中随机提取一些文件?我已经查过了,找不到更好的方法。

谢谢。

这将为您提供文件夹中的名称列表,其中 mypath 是文件夹的路径。

from os import listdir
from os.path import isfile, join
from random import shuffle
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
shuffled = shuffle(onlyfiles)
small_list = shuffled[:len(shuffled)/10]

这应该有效

您可以使用以下策略:

  1. 使用 list = os.listdir(path) 获取目录中的所有文件作为路径列表。
  2. 接下来,使用 range = len(list) 函数计算您的文件数。
  3. 使用 rangenumber 你可以获得这样的随机项目编号 random_position = random.randrange(1, range)
  4. 重复第 3 步并将值保存在列表中,直到获得足够的位置(range/10 在您的情况下)
  5. 之后你可以得到像这样的所需文件名list[random_position]

使用循环 for 进行迭代。

希望对您有所帮助!

使用 numpy.random.choice(array, N) 你可以从数组中随机 select N 项。

import numpy as np
import os

# list all files in dir
files = [f for f in os.listdir('.') if os.path.isfile(f)]

# select 0.1 of the files randomly 
random_files = np.random.choice(files, int(len(files)*.1))

我无法使用其他方法轻松处理我的代码,但我想到了这个。

output_folder = 'C:/path/to/folder'
for x in range(int(len(files) *.1)):
    to_copy = choice(files)
    shutil.copy(os.path.join(subdir, to_copy), output_folder)            

基于 Karl 的解决方案(在 Win 10 下对我不起作用,Python 3.x),我想到了这个:

import numpy as np
import os

# List all files in dir
files = os.listdir("C:/Users/.../Myfiles")

# Select 0.5 of the files randomly 
random_files = np.random.choice(files, int(len(files)*.5))

# Get the remaining files
other_files = [x for x in files if x not in random_files]

# Do something with the files
for x in random_files:
    print(x)