Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to randomly select a file in python

I am intermediate when it comes to python but when it comes to modules I struggle. I'm working on a project and I'm trying to assign a variable to a random directory or file within the current directory (any random thing within the directory). I would like it to just choose any random thing in that directory and then assign it to a variable.

The product should end up assigning a variable to a random object within the working directory. Thank you.

file = (any random file in the directory)

Edit: This works too

_files = os.listdir('.')
number = random.randint(0, len(_files) - 1)
file_ = _files[number]

Thank you everyone that helped :)

like image 807
Not The_Man Avatar asked Nov 26 '25 14:11

Not The_Man


1 Answers

Another option is to use globbing, especially if you want to choose from some files, not all files:

import random, glob
pattern = "*" # (or "*.*")
filename = random.choice(glob.glob(pattern))
like image 195
DYZ Avatar answered Nov 28 '25 03:11

DYZ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!