How to select file randomly from multiple sub-folders

Viewed 875

I've multiple sub-folders and each sub-folder has multiple files. I need to select the sub-folder randomly and then need to select a random file in that sub-folder. Let's say I've five folders A, B, C, D, E, and each folder contains another folder named data and this data folder contains multiple files. I need to pick the folder randomly from the five folders and then open the data folder and finally randomly select a file.

4 Answers

Keep the folder names in a list. import random import os folders = [0,1,2,3,4] selected_folder = random.choice(folders) path = selected_folder+"/data"

Now to take random file from the path, do random.choice() and pass the list of files in that path. Use os.listdir(path) to get the list of files.


import os
import random

path = os.getcwd()

def getRandomFile(path):
    randomDir = random.choice([(x) for x in list(os.scandir(path)) if x.is_dir()]).name
    randomFile = random.choice([f for f in list(os.scandir(randomDir + "\\data\\"))]).name
    return randomFile

print(getRandomFile(path))

Try this: (Python file must be in the same main folder as those 5 folders)

import os,random
lst=list(filter(lambda x: os.path.isdir(x), os.listdir('.'))) //get folder list
folder=random.choice(lst) //select random folder
os.chdir(os.path.join(os.path.dirname(__file__), folder, 'data')) // goto random folder/data
lst=list(filter(lambda x: os.path.isfile(x), os.listdir('.'))) //get file list
file=random.choice(lst) //get random file
print(file)

As I understand, you actually need 4 functions to build your block of code:

  • os.listdir(path) which list all files and directories at a location
  • os.path.isdir(path) to check if a element in a location is a directory
  • os.path.isfile(path) idem with a files
  • random.randrange(X) to find a random number in the range [0; X[

I'm sure you can find easily the doc concerning those functions as they are all in the standard library of python. Anyway here is your code:

import os
import random

path = "/home/johndoe/"
dirs  = list(filter(lambda dir: os.path.isdir(os.path.join(path, dir)), os.listdir(path)))

dir_chosen = dirs[random.randrange(len(dirs))]

files_path = os.path.join(path, dir_chosen, "data")
files = list(filter(lambda file: os.path.isfile(os.path.join(files_path, file)), os.listdir(files_path)))

file_chosen = files[random.randrange(len(files))]

print("the file randomly chosen is: {}".format(os.path.join(files_path, file_chose )))

You can also check about os.path.join(a, b) if you don't know about it but it is basically equivalent to a + '/' + b on UNIX and a + '\' + b on Windows.

Related