# Python randomization

This topic is 3835 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi, I'm currently using something along the lines of random.choice([1,2,3]) However, i have a load of directories and i would like to randomly get the name of one of the directories. For example if i have directories "a", "b" and "c"; I could use something like.. directory = random.choice(["a","b","c"]) However their are hundreds of directories and more are added frequently. How would I get a list of the directories and randomly select one? Thanks in advance =)

##### Share on other sites
Is your question about how to get a random element from a list or about how to get a list of directories without hand-writing it? You seem to already know the former, so maybe your subject is misleading. To get file and directory listings we'll need to use the os module.
import osmylist = os.listdir("C:\\Somewhere")

Ok, so mylist holds a list of file and folder names under the given path "C:\Somewhere". That's not quite good enough because you only want folders, right? You'll have to iterate the list and identify folders. There is a handy path.isdir function for that. It will need a full path, so you'll also want to use the path.join function.
import osimport randompath = "C:\\Somewhere"dirs = []for filename in os.listdir(path):    fullpath = os.path.join(path, filename)    if os.path.isdir(fullpath):        dirs.append(fullpath)randomdir = random.choice(dirs)

You'll probably need to tweak this for your purposes, but that should give you the general idea. Read the os module docs for more.

##### Share on other sites
Nice one. This worked a treat for me. Thanks a lot =)

1. 1
2. 2
3. 3
Rutin
15
4. 4
5. 5

• 10
• 9
• 9
• 11
• 11
• ### Forum Statistics

• Total Topics
633682
• Total Posts
3013309
×