Answer a question

What is the best way to choose a random file from a directory in Python?

Edit: Here is what I am doing:

import os
import random
import dircache

dir = 'some/directory'
filename = random.choice(dircache.listdir(dir))
path = os.path.join(dir, filename)

Is this particularly bad, or is there a particularly better way?

Answers

import os, random
random.choice(os.listdir("C:\\")) #change dir name to whatever

Regarding your edited question: first, I assume you know the risks of using a dircache, as well as the fact that it is deprecated since 2.6, and removed in 3.0.

Second of all, I don't see where any race condition exists here. Your dircache object is basically immutable (after directory listing is cached, it is never read again), so no harm in concurrent reads from it.

Other than that, I do not understand why you see any problem with this solution. It is fine.

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐