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").
-
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 accordinglyAlmog-at-Nailo– Almog-at-Nailo2020-05-13 11:53:24 +00:00Commented May 13, 2020 at 11:53
-
2Welcome to SO! Please use code snippets instead of images, it makes it easier to look. Thanks!rusito23– rusito232020-05-13 11:54:58 +00:00Commented 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 manSyed Ammad Ali– Syed Ammad Ali2020-05-13 12:28:37 +00:00Commented May 13, 2020 at 12:28
2 Answers
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.
2 Comments
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.