Jump to content
  • Advertisement
Sign in to follow this  
Mr T 87

Python randomization

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
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 os
mylist = 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 os
import random

path = "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 this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!