Not The_Man
Not The_Man

Reputation: 41

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 :)

Upvotes: 3

Views: 5375

Answers (4)

JimsJump
JimsJump

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

Not The_Man
Not The_Man

Reputation: 41

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

Line by line order:

  1. It puts all the files in the directory into a list
  2. Chooses a random number between 0 and the length of the directory - 1
  3. Assigns _file to a random file

Upvotes: 1

rlee827
rlee827

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

DYZ
DYZ

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

Related Questions