如何从文件夹中显示随机图片(Python)

the*_*ggg 2 python

我必须使用Python从文件夹中显示随机图像.我试过了

import random, os
random.choice([x for x in os.listdir("path")if os.path.isfile(x)])
Run Code Online (Sandbox Code Playgroud)

但它对我不起作用(它给出了Windows错误:错误的目录语法,即使我刚复制并粘贴).

哪个可能是问题?

fal*_*tru 7

您需要指定正确的相对路径:

random.choice([x for x in os.listdir("path")
               if os.path.isfile(os.path.join("path", x))])
Run Code Online (Sandbox Code Playgroud)

否则,代码将尝试image.jpg在当前目录中找到files()而不是"path"目录(path\image.jpg).

UPDATE

正确指定路径.特别是逃避反斜或使用r'raw string literal'.否则\..被解释为转义序列.

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)
Run Code Online (Sandbox Code Playgroud)