Reputation: 41
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 :)
Upvotes: 3
Views: 5375
Reputation: 31
Here is an option to print and open a single random file from directory with mulitple sub-directories.
import numpy as np
import os
file_list = [""]
for root, dirs, files in os.walk(r"E:\Directory_with_sub_directories", topdown=False):
for name in files:
file_list.append(os.path.join(root, name))
the_random_file = file_list[np.random.choice(len(file_list))]
print(the_random_file)
os.startfile(the_random_file)
Upvotes: 0
Reputation: 41
_files = os.listdir('.')
number = random.randint(0, len(_files) - 1)
file_ = _files[number]
Line by line order:
Upvotes: 1
Reputation: 1873
You can use
import random
import os
# random.choice selects random element
# os.listdir lists in current directory
filename=""
# filter out directories
while not os.path.isfile(filename):
filename=random.choice(os.listdir(directory_path))
with open(filename,'r') as file_obj:
# do stuff with file
Upvotes: 4
Reputation: 57033
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))
Upvotes: 6