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

phy*_*xic 6 python random sampling

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

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

谢谢。

Kar*_*nka 10

使用numpy.random.choice(array, N)您可以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))
Run Code Online (Sandbox Code Playgroud)


phy*_*xic 2

我无法让其他方法轻松地使用我的代码,但我想出了这个。

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)            
Run Code Online (Sandbox Code Playgroud)