Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
issue with PIL
#1
Hi,
I was wondering if someone can explain this issue I'm having.
So practically, when I run the following code:
from PIL import Image
from os import listdir
for picture in listdir('New_folder'):
    print(picture)
the code runs fine and gives me the correct output.
However, when I change the code to this:
for picture in listdir('New_folder'):
    img = Image.open(picture)
    img.show()
I get the following error:
FileNotFoundError: [Errno 2] No such file or directory:
I really can't figure out what I am doing wrong.
Thanks.
Reply
#2
os.listdir returns the names of the files in the target directory, not the full path to it. To open the file, you need the full path.

import os

dir = "dir"
for file in os.listdir(dir):
    print(file)
    fullpath = os.path.join(dir, file)
    text = open(fullpath).readlines()
    print(text)
Output:
$ cat a.txt cat: a.txt: No such file or directory $ cat dir/a.txt Hello $ python3 file.py a.txt ['Hello\n']
Reply
#3
That helps a lot and makes it all so much clear now! Thanks so much for taking the time to explain it to me.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020