在 Python 中从目录中选择随机文件的最佳方法是什么?
编辑:这是我正在做的:
import os
import random
import dircache
dir = 'some/directory'
filename = random.choice(dircache.listdir(dir))
path = os.path.join(dir, filename)
这是特别糟糕,还是有特别好的方法?
最佳答案
import os, random
random.choice(os.listdir("C:\\")) #change dir name to whatever
关于您编辑的问题:首先,我假设您知道使用 dircache
的风险,以及它是 deprecated since 2.6, and removed in 3.0 的事实。 .
其次,我看不到这里存在任何竞争条件。您的 dircache
对象基本上是不可变的(目录列表被缓存后,它不再被读取),因此从它的并发读取中没有任何危害。
除此之外,我不明白为什么您认为此解决方案有任何问题。没关系。
关于python - 从目录中选择随机文件的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/701402/