I have a folder in a specified directory containing several PNGs that need to be opened randomly. I can't seem to get random.shuffle
to work on the folder. I have thus far been able to print
the contents, but they need to also be randomized so when they are opened, the sequence is unique.
Here's my code:
import os, sys
from random import shuffle
for root, dirs, files in os.walk("C:\Users\Mickey\Desktop\VisualAngle\sample images"):
for file in files:
if file.endswith(".png"):
print (os.path.join(root, file))
This returns a list of the images in the folder. I'm thinking maybe I could somehow randomize the output from print
and then use open
. I have so far failed. Any ideas?
I have a folder in a specified directory containing several PNGs. You don't need and should not be using os.path.walk
searching a specific directory, it would also potentially add files from other subdirectories which would give you incorrect results. You can get a list of all png's using glob and then shuffle:
from random import shuffle
from glob import glob
files = glob(r"C:\Users\Mickey\Desktop\VisualAngle\sample images\*.png")
shuffle(files)
glob
will also return the full path.
You could also use os.listdir
to search the specific folder:
pth = r"C:\Users\Mickey\Desktop\VisualAngle\sample images"
files = [os.path.join(pth,fle) for fle in os.listdir(pth) if fle.endswith(".png")]
shuffle(files)
To open:
for fle in files:
with open(fle) as f:
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With