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 


The random picture output will be shown for example:

How to show random picture from a folder in Python


  • 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:

One response to “How to show random picture from a folder in Python”

  1. bettina says:

    it did not work, but Fahim found the solution on
    on the mp3 page
    June 1, 2021 at 2:28 pm

    I Have the solution of error !!
    Just replace :-
    with :-
    os.startfile(f”# path were is music is located#{d}”)
    in my case it was :-
    os.startfile(f”C:/Users/Kazi Fahim/Music/mp3/{d}”)

Leave a Reply

Your email address will not be published. Required fields are marked *