How to randomly select files from folder using Python

While doing image processing using python, I wanted to select image file randomly from images folder. I found couple of ways of doing this but following is the simplest way to get random file name


import os
import random

path ='/code/github/python'
files = os.listdir(path)
index = random.randrange(0, len(files))



One Reply to “How to randomly select files from folder using Python”

  1. Thanks, your answer inspired me!
    I’m afraid the program might have a bug since randrange() method excludes the last item if the sequence.
    I think the bug could be resolved by just adding a +1 to it:

    index = random.randrange(0, len(files)+1)

    I. also, found that Python has some more convenient sampling methods in the same library i.e. random.sample(population, k) which is used to select k number of elements from a population without replacement. Likewise, random.choices() is used to select items with replacement.

    Anyhow, thanks a million. Your answer did help me.

Leave a Reply

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