Python FileNotFoundError:[Errno 2]没有这样的文件或目录:';second-5.jpg';尝试显示随机图像时

Python FileNotFoundError:[Errno 2]没有这样的文件或目录:';second-5.jpg';尝试显示随机图像时,python,python-3.x,Python,Python 3.x,你好。我需要从我有7.jpg文件的目录(onedir或fivedir)中打开一个随机图像,并在图像查看器中显示它 from PIL import Image import os directory_five = "C:/Users/pc/PycharmProjects/project/fivedir/" directory_one = "C:/Users/pc/PycharmProjects/pro

你好。我需要从我有7.jpg文件的目录(onedir或fivedir)中打开一个随机图像,并在图像查看器中显示它

            from PIL import Image
            import os

            directory_five = "C:/Users/pc/PycharmProjects/project/fivedir/"
            directory_one = "C:/Users/pc/PycharmProjects/project/onedir/"
            #and the same for 3 more dirs

            if(namchar in pull): #namchar is in pull
                if(str(five) in pull): #five is in pull
                     random_image = random.choice(os.listdir(directory_five))
                     img = Image.open(random_image)
                     img.show()
                elif(str(one) in pull): #one is in pull,too
                    random_image = random.choice(os.listdir(directory_one))
                    img = Image.open(random_image)
                    img.show()
                elif(.... #and the same for several times
所以,我的代码似乎一直在工作,直到它必须打开一个图像。我收到一个错误:文件“C:/Users/pc/PycharmProjects/project/main.py”,第75行,随机抽取 img=图像。打开(随机图像) 文件“C:\Users\pc\AppData\Local\Programs\Python37\lib\site packages\PIL\Image.py”,第2766行,处于打开状态 fp=内置的.open(文件名为“rb”) FileNotFoundError:[Errno 2]没有这样的文件或目录:“second-5.jpg”


如何解决?谢谢

random_image
只是文件名;它不包括目录路径。您需要
Image.open(directory\u five+“/”+random\u Image)
。random\u Image将只是文件名,它不包含文件的填充路径。因此,您需要获取文件名并将其与目录名连接起来,然后使用该名称打开文件
img=Image.open(directory\u five+random\u Image)