有人知道如何访问文件夹中的随机图像吗?
我想做的是在用户输入后显示随机图像。图像已经存储在已加载到PyCharm的文件夹中,并且在我的桌面上有一个文件。
我在下面的网上找到了此代码,但是我不确定100%如何使用它。
import os
import random
path="C:\\Users\\sairajesh\\Desktop\\image"
files=os.listdir(path)
d=random.choice(files)
d.show
感谢您在这里的任何帮助!您可以在下面看到我的错误。我正在使用Mac。另外,我是编程新手,所以请不要判断。
这是我得到的错误:
Traceback (most recent call last):
File "/Users/kimtran/PycharmProjects/final/Where to eat.py", line 66, in <module>
main()
File "/Users/kimtran/PycharmProjects/final/Where to eat.py", line 45, in main
files =os.listdir(path)
FileNotFoundError: [Errno 2] No such file or directory: '/Users/kimtran/Desktop/pics'
答案 0 :(得分:1)
您的代码应该可以正常工作,但d.show
除外,我不知道您要怎么做。而且您的路径是Windows路径格式,而不是您Mac上的路径格式。
import os
import random
from PIL import Image
path = './imagefolder' # in case the folder is in the same directory as the script
files = os.listdir(path) # listdir gives you a list with all filenames in the provided path.
randomFile = random.choice(files) # random.choice then selects a random file from your list
print(randomFile) # prints the random filename
image = Image.open(path + '/' + randomFile) # displayed the image
image.show()
警告randomFile只是作为字符串的文件名,而不是实际的文件。