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?
Right-click the folder in the left-hand pane — not the right — and click the new “Select Random” option. RandomSelectionTool then selects something from the contents of that folder — either a file, or a folder — and the right-hand pane should be updated to display it.
On first run you select to add it to Windows Explorer and find that option available when you right-click in a folder in the file browser. There you find listed the new select random menu option. Selecting it picks a random file that is stored in the directory.
Click the first file or folder you want to select. Hold down the Shift key, select the last file or folder, and then let go of the Shift key. Hold down the Ctrl key and click any other file(s) or folder(s) you would like to add to those already selected.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With