'Python FileNotFoundError: [Errno 2] No such file or directory: 'post.jpg' but he found it there [duplicate]

Dear stackoverflow community, I have the following problem. I tried to select a random image from my 'uploads' folder. With this line of code:

upload = random.choice(os.listdir("/Instagram Bot/Quote Script/upload/"))

I also tried

upload = random.choice(os.listdir("C:\\Instagram Bot\\Quote Script\\upload\\"))

but I keep getting this error:

with open(fname, "rb") as fhandle:
FileNotFoundError: [Errno 2] No such file or directory: 'post.jpg'

The funny thing is that I didn't specify that picture exactly, but he still found a picture (which is actually in the folder) but says it is not in the folder. What can I do? Best wishes.



Solution 1:[1]

upload = random.choice(os.listdir("/Instagram Bot/Quote Script/upload/"))

This line will return you a file name something like example.txt. If you now want to open the file you have to enter a relativ path or a the whole paht so if you want to open it try something like

with open("C:\\Instagram Bot\\Quote Script\\upload\\"+fname, "rb") as fhandle:
    #TODO Write some code

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yanni2