Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Random pictures from a file
#3
Can show demo of a generic solution.
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
Reply


Messages In This Thread
Random pictures from a file - by aliwien - Apr-23-2021, 11:37 AM
RE: Random pictures from a file - by supuflounder - Apr-23-2021, 12:52 PM
RE: Random pictures from a file - by snippsat - Apr-23-2021, 06:00 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Python logging RotatingFileHandler writes to random file after the first log rotation rawatg 0 419 Feb-15-2024, 11:15 AM
Last Post: rawatg
  Find a shift between 2 pictures TazFleck 0 1,169 Jan-18-2023, 09:56 PM
Last Post: TazFleck
Photo put a green boarder and text around multiple pictures jackosullivan 5 1,488 Jul-05-2022, 10:39 AM
Last Post: snippsat
  Help with taking pictures on raspberry pi octavia 1 1,705 Feb-07-2020, 04:54 PM
Last Post: Larz60+
  client-server pictures mcgrim 4 2,993 Oct-25-2019, 09:53 PM
Last Post: micseydel
  Print random musik to wav file Pereskia 2 2,686 Mar-27-2019, 11:53 AM
Last Post: Pereskia
  Open Pictures with Python MaxouRuEnIpTF34 1 3,056 Apr-22-2018, 07:48 PM
Last Post: Gribouillis
  Write selected (random) columns to output-file anjohepa 0 2,351 Feb-27-2018, 02:19 PM
Last Post: anjohepa
  Comparing pictures pedro 1 2,750 Sep-11-2017, 07:51 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020