Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to choose a random file from a directory

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?

like image 945
JasonSmith Avatar asked Mar 31 '09 14:03

JasonSmith


People also ask

How do I randomly select files in a folder?

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.

How do I select a random file?

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.

How do I randomly select files in Windows?

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.


1 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.

like image 182
Yuval Adam Avatar answered Oct 02 '22 14:10

Yuval Adam