0

Hello i need help with a very simple Python 3 script. In the script i try open a png image file from a folder with this:

png = Image.open('img/image.png', + 'r')

It's work good, but now i need get random .png images from same folder, but after some unsuccessful try, I'll like know how do it, actually i use in my script

  • from random import randint
  • import uuid
  • from PIL import Image

Any help will be appreciated, thank you all

Stew
  • 95
  • 1
  • 2
  • 9
  • Can you show the exact code you tried, and describe how exactly it failed (exception, unexpected results, etc)? – glibdud Jan 30 '19 at 16:57
  • 1
    [List all the `.png` in a directory](https://stackoverflow.com/a/27593246/7501501) then [pick a random item from the list](https://pynative.com/python-random-choice/). – Yonlif Jan 30 '19 at 17:03
  • 1
    Get a list of the file names in the folder with `glob.glob()` and then use `random.choice()` to pick one of them. – martineau Jan 30 '19 at 17:04

2 Answers2

5
import glob
import random
from PIL import Image
img = random.choice(glob.glob('img/*.png'))
png = Image.open(img, + 'r')
Kays Kadhi
  • 538
  • 6
  • 21
1
import os,random
from PIL import Image
random_image = random.choice(os.listdir("img"))
Image.open(random_image)