random - How can I open a series of files (PNGs) from a specified directory (randomly) using Python? -


i have folder in specified directory containing several pngs need opened randomly. can't seem random.shuffle work on folder. have far been able print contents, need randomized when opened, sequence unique.

here's code:

import os, sys random import shuffle  root, dirs, files in os.walk("c:\users\mickey\desktop\visualangle\sample images"):     file in files:         if file.endswith(".png"):             print (os.path.join(root, file)) 

this returns list of images in folder. i'm thinking maybe somehow randomize output print , use open. have far failed. ideas?

i have folder in specified directory containing several pngs. don't need , should not using os.path.walk searching specific directory, potentially add files other subdirectories give incorrect results. can list of png's using glob , shuffle:

from random import shuffle glob import glob files = glob(r"c:\users\mickey\desktop\visualangle\sample images\*.png") shuffle(files) 

glob return full path.

you use os.listdir search specific folder:

pth = r"c:\users\mickey\desktop\visualangle\sample images" files = [os.path.join(pth,fle) fle in os.listdir(pth) if fle.endswith(".png")] shuffle(files) 

to open:

for fle in files:    open(fle) f:         ... 

Comments