How can I open a series of files (PNG) from a specified directory (by accident) using Python?

I have a folder in the specified directory containing several PNGs that need to be opened randomly. I can't seem to random.shuffle

work with this folder. So far I have been able to print

content, but they must be randomized as well, 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))

      

Returns a list of images in a folder. I think maybe I could somehow randomize the output from print

and then use open

. I still haven't been able to. Any ideas?

+3


source to share


2 answers


I have a folder in the specified directory containing multiple PNGs. You don't need to and shouldn't use os.path.walk

to search in a specific directory, it could also potentially add files from other subdirectories, which would give you incorrect results. You can get a list of all pngs 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 can also use os.listdir

to search in a 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:
        ...

      

+4


source


You can first create a list of filenames png

and then shuffle:



import os
from random import shuffle

dirname = r'C:\Users\Mickey\Desktop\VisualAngle\sample images'

paths = [
    os.path.join(root, filename)
    for root, dirs, files in os.walk(dirname)
    for filename in files
    if filename.endswith('.png')
]
shuffle(paths)
print paths

      

+5


source







All Articles