How to show random picture from a folder in Python

This tutorial is about how to show a random picture from a folder in Python. Python contains a lot of Predefined modules. Python has a module that is the random module by using the random module to show a random picture from a folder.

The following are constraints to get a random picture:

  • The picture folder path must be specified to open the picture on the computer.
  • By using random.choice() method to select a particular picture present in the folder.
  • All the pictures must be stored in the .py file location to start the picture using the OS module otherwise you must change to picture folder location using change directory to start the picture.

Importing Random Module:

So, let’s have a look at importing the random module:

import random

Importing random module in .py file

Importing OS Module:

So, let us have a look at importing the OS module:

import random
import os

Importing os module in .py file

Folder details:

The folder contains a lot picture (.jpg) or (.png) by using random function a particular picture is selected show the picture using OS module

#-----------------Inside the folder-----------
image 1
image 2
image 3

Example to show a random picture from a folder in Python:

import os
import random 
path="C:\\Users\\sairajesh\\Desktop\\image"
files=os.listdir(path)
d=random.choice(files)
os.startfile(d)

output:

The random picture output will be shown for example:

How to show random picture from a folder in Python

Explanation:

  • First, you select the path of the folder where the picture is present like->c\\user\\folder
  • By using the listdir() method store all the images present in the folder
  • By using random.choice() method to select a image and os.startfile() method to show the image.

OS.Start file() method:

The os.startfile() method will be used to run files present in the folder directly on the default opener of the file.

Also read:

Leave a Reply