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?
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
dircacheobject 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.