Apr-23-2021, 06:00 PM
Can show demo of a generic solution.
Let say have a folder
So when
Let say have a folder
animal
that have sub-folder like dog_pic, cat_pic...ect. So when
dog
is the chosen word pick a random image from dog_pic
folder.import os import random def folder_pic(path, name_choice): '''Choice right animal folder''' for folder in os.scandir(path): if os.path.isdir(folder): if name_choice in folder.name: return folder.name def pick_random_animal(path, animal_folder): '''Get a random image from animal folder''' path = os.path.join(path, animal_folder) pic = random.choice(os.listdir(path)) return pic if __name__ == '__main__': path = r'E:\div_code\animals' name_choice = 'dog' animal_folder = folder_pic(path, name_choice) print(pick_random_animal(path, animal_folder))
Output:# Run 3 times
dog_2.png
dog_1.png
dog_3.png
So if change name_choice = 'cat'
will pic from cat_pic
folder.Output:# Run 3 times
cat_1.png
cat_4.png
cat_4.png