静态案例
如果文件列表被假定为“冻结”(不会删除/添加任何文件),那么我们可以使用os.listdir + hypohtesis.strategies.sampled_from like
import os
from hypothesis import strategies
directory_path = 'path/to/directory/with/txt/files'
txt_files_names = strategies.sampled_from(sorted(os.listdir(directory_path)))
或者如果我们需要完整路径
from functools import partial
...
txt_files_paths = (strategies.sampled_from(sorted(os.listdir(directory_path)))
.map(partial(os.path.join, directory_path)))
或者如果目录可能有不同扩展名的文件,我们只需要 .txt 我们可以使用glob.glob
import glob
...
txt_files_paths = strategies.sampled_from(sorted(glob.glob(os.path.join(directory_path, '*.txt'))))
动态案例
如果目录内容可能发生变化,并且我们希望在每次数据生成尝试时进行目录扫描,可以这样做
dynamic_txt_files_names = (strategies.builds(os.listdir,
strategies.just(directory_path))
.map(sorted)
.flatmap(strategies.sampled_from))
或使用完整路径
dynamic_txt_files_paths = (strategies.builds(os.listdir,
strategies.just(directory_path))
.map(sorted)
.flatmap(strategies.sampled_from)
.map(partial(os.path.join, directory_path)))
或glob.glob
dynamic_txt_files_paths = (strategies.builds(glob.glob,
strategies.just(os.path.join(
directory_path,
'*.txt')))
.map(sorted)
.flatmap(strategies.sampled_from))
编辑