如何从文件夹中随机显示一张图片?

5 投票
1 回答
20292 浏览
提问于 2025-04-28 13:50

我需要用Python从一个文件夹里显示一张随机图片。我试过了

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

但是对我来说不管用(它给我报了Windows错误:目录语法错误,尽管我只是复制粘贴了)。

这可能是什么问题呢……

暂无标签

1 个回答

9

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

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

否则,代码会在当前目录中寻找文件(image.jpg),而不是在"path"目录中(path\image.jpg)。

更新

一定要正确指定路径。特别是要处理好反斜杠,或者使用r'原始字符串'。否则\..会被当作转义序列来解释。

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)

撰写回答