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!
CodePudding user response:
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