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://*.com/questions/26467804/how-to-display-a-random-picture-from-a-folder

上一篇:JUC笔记(How)


下一篇:如何创建一个像链接一样的HTML按钮? [英]How to create an HTML button that acts like a link?