1. 程式人生 > 實用技巧 >How to display a random picture from a folder?

How to display a random picture from a folder?

天涯浪子 提交於 2020-12-09 20:38:40

問題


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


回答1:


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)


轉載來源:https://stackoverflow.com/questions/26467804/how-to-display-a-random-picture-from-a-folder