简体   繁体   中英

Python PIL open image from specific file

I'm getting to grips with the Pillow library from Python. I have a folder (folder 1) where the code is stored and within that folder another folder (folder 2) where all the pictures I would like to edit/manipulate are.

However, I have only been able to access the images when they are saved in folder 1, but not when they are only saved in folder 2.

I have used the code:

from PIL import Image
import os

for k in os.listdir('.'):
    if k.endswith('.jpg'):
        i = Image.open(k)
        kn, kext = os.path.splitext(k)
        print(kn)

Which prints the names of all the file names minus the '.jpg' extension:

MeisJeMetDeParel
StarryNight
TheSonOfMan

I have then tried to do the same, only accessing the images from inside their own specific folder:

for k in os.listdir('testPictures'):
    if k.endswith('.jpg'):
        i = Image.open(k)
        kn, kext = os.path.splitext(k)
        print(kn)

by changing the directory to the name of the folder they are stored in (testPictures). However, I get the error:

FileNotFoundError: [Errno 2] No such file or directory: 'MeisJeMetDeParel.jpg'

So it seems that the image within the folder is being accessed, as it has been able to identify the name of the first image in the folder, yet the code is unable to print the names of the images as it was able to do so when both the code and the images were saved together. What adjustments can I make to my code so that the pictures in the testPictures folder can be printed? Thanks

The os.listdir function returns a path relative to the directory you specified so you have to os.path.join the directory to the name you got:

for k in os.listdir('testPictures'):
    if k.endswith('.jpg'):
        i = Image.open(os.path.join('testPictures', k))
        kn, kext = os.path.splitext(k)
        print(kn)

I might suggest that instead of calling os.listdir and checking the extension manually you could use the glob module instead and also avoid having to os.path.join the directory name:

import glob
for k in glob.glob('testPictures/*.jpg'):
    i = Image.open(k)
    kn, kext = os.path.splitext(k)
    print(kn)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM