Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display a random picture from a folder?

Tags:

python

I have to display a random image from a folder using Python. I've tried

import random, os
random.choice([x for x in os.listdir("path")if os.path.isfile(x)])

but it's not working for me (it gives Windows Error: wrong directory syntax, even though I've just copied and paste).

Which could be the problem...

like image 908
giulia_dnt Avatar asked Oct 20 '14 14:10

giulia_dnt


1 Answers

You need to specify correct relative path:

random.choice([x for x in os.listdir("path")
               if os.path.isfile(os.path.join("path", x))])

Otherwise, the code will try to find the files (image.jpg) in the current directory instead of the "path" directory (path\image.jpg).

UPDATE

Specify the path correctly. Especially escape backslashes or use r'raw string literal'. Otherwise \.. is interpreted as a escape sequence.

import random, os
path = r"C:\Users\G\Desktop\scientific-programming-2014-master\scientific-programming-2014-master\homework\assignment_3\cifar-10-python\cifar-10-batches-py"
random_filename = random.choice([
    x for x in os.listdir(path)
    if os.path.isfile(os.path.join(path, x))
])
print(random_filename)
like image 66
falsetru Avatar answered Sep 29 '22 07:09

falsetru