0

Hope you all are good. I'm facing this problem while importing images from a directory inside my project directory. I don't what's the problem. I did this while putting the images in the main directory. It's worked perfectly fine but I want to now import images from my folder images . Here is the screenshot. I hope you all can understand what i'm trying to do The only problem is in that "if items.endswith("images.jpg").

3
  • I think i understand what you're trying to do. look at the output you get from os.listdir("images"). it's probably different than what you expect. try to print the output first and then change the "endswith()" statement accordingly Commented May 13, 2020 at 11:53
  • 2
    Welcome to SO! Please use code snippets instead of images, it makes it easier to look. Thanks! Commented May 13, 2020 at 11:54
  • @AlmogAtNailo bro it worked perfectly when my images were in the main directory when they were not in the folder(images) after that it came into my mind what if these pics were in some kinda folder so i made a folder and gave the path but after that its neither showing the error nor giving the output just ends the program very hectic it is man Commented May 13, 2020 at 12:28

2 Answers 2

1

Try this :

for items in os.listdir('images'):
    if items.endswith('.jpg'):
        image = Image.open(f'images/{items}')

Explanation:
os.listdir returns the files inside the directory which doesn't include the full path. ie. images/images.jpg.
So when using PIL you should add the master path at the beginning.

Sign up to request clarification or add additional context in comments.

2 Comments

OH THANK YOU IT WORKED HAHAHAHA GOD BLESSS YOUUUU
That's awesome. Can you mark this answer ? check mark at the left :-)
0

I can see there are two main problems, the first one is that you are checking the file extension with endswith('images/.jpg'), this should be endswith('.jpg'), the second one is that you are using os.listdir, which returns a list with the file names in the folder and not the full path, that means that you are trying to load the image from im_name.jpg and not images/im_name.jpg.

The solution to both of these problems would be to use the glob package, which lets you search for all files matching an extension, and returns the full path for each file. For example:

import glob

print(glob.glob('images/*.jpg'))

should print:

images/image1.jpg
images/image2.jpg
...

And these are enough to load them using PIL.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.