IOError when using imghdr module in Python

462 views Asked by At

This is my code used to check the format of files stored in many folders:

check_image_format():

import imghdr as ih

def check_image_format(image_dir):
    for root, dirs, files in os.walk(image_dir):
        for image in files:
            format = ih.what(image)
            if format != 'jpeg' or format != 'png':
                return -1
    return 0

main():

def main(_):
    # Check the correct format of images
    ret = check_image_format('img_dir')
    if(ret == -1):
         print("Some images are not in the correct format. Please check")

my img_dir is the root directory of others three subfolders containing the images I want to check. When I launch the program I received this error:

IOError: [Errno 2] No such file or directory: img_1.jpg

But the file exists and is inside a subfolder. What is the reason of this error ?

1

There are 1 answers

1
mvelay On BEST ANSWER

You need to build absolute path for your current image path:

import imghdr as ih

def check_image_format(image_dir):

    for root, dirs, files in os.walk(image_dir):
        for image in files:
            format = ih.what(os.path.join(root, image))
            if format != 'jpeg' or format != 'png':
                return -1
    return 0