giulia_dnt
giulia_dnt

Reputation: 197

How to display a random picture from a folder?

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...

Upvotes: 5

Views: 20486

Answers (1)

falsetru
falsetru

Reputation: 369054

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)

Upvotes: 9

Related Questions