py's blog

sh∅ut

Best way to choose a random file from a directory

使用 glob.glob() 过滤文件扩展名

ref: https://stackoverflow.com/questions/701402/best-way-to-choose-a-random-file-from-a-directory

如果目录不需要过滤

1
2
3
4
import os, random
path_to_dir = 'path/to/dir'
file_name = random.choice(os.listdir(path_to_dir))
file_path = os.path.join(path_to_dir, file_name)

如果只需要一种类型的文件

1
2
3
import glob, random
path_to_dir = 'path/to/dir'
file_path = random.choice(glob.glob(path_to_dir, '*.jpg'))