Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 511
Mickey Avatar asked Dec 19 '22 02:12

Mickey


1 Answers

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:
        ...
like image 193
Padraic Cunningham Avatar answered Dec 26 '22 11:12

Padraic Cunningham