0

i'm trying to make something that returns a random image from a folder to eventually put together an outfit. the path is a specific folder, as each path is a different type of clothing article (i.e. a folder/path for pants would be /Users/xxx/Desktop/outfit_images/5pants)

def article(path):
    files = os.listdir(path)  # listdir gives you a list with all filenames in the provided path.
    randomFile = random.choice(files)  # random.choice then selects a random file from your list
    image = Image.open(path + '/' + randomFile)  # displayed the image
    return image

i'm using the code above to have the specified clothing article file as the input, and then select a random image from that file. i however, get errors (.DS_Store selection error) every few attempts becuase of the hidden files on the mac '.', '..', and want to figure out how to avoid selecting these hidden files. i would prefer to use a method other than running the rm from the terminal. any help is greatly appreciated!

  • You can just ignore it by checking `.` or check if the file is not an image, lastly but not least you can check if the file is hidden https://stackoverflow.com/questions/284115/cross-platform-hidden-file-detection – Adarsh Raj Jul 30 '22 at 16:11

1 Answers1

1

You can use glob for this:

import glob
import os

def article(path):
    files = glob.glob(os.path.join(path, '*'))
    randomFile = random.choice(files)  
    image = Image.open(path + '/' + randomFile)  
    return image
Adarsh Raj
  • 325
  • 4
  • 17