0

I'm trying to create a simple script to pull EXIF information out from multiple jpeg files at once, but I'm getting "IOError: cannot identify image file" when trying to use a variable instead of an absolute path. Here's the code that I'm using:

import os
from PIL import Image, ExifTags

source = raw_input("Enter the path to scan")
os.chdir(source)
for root, dirs, files in os.walk(source):
    for file_name in files:
        img = Image.open(file_name)
        exif = { ExifTags.TAGS[k]: vars for k, vars in img._getexif().items() if k in ExifTags.TAGS }
        print exif

I have also tried using StringIO per a tip I noticed while Google searching my problem. The code is the same as above except I import StringIO and make the following change in the Image.open code:

img = Image.open(StringIO(file_name))

This did not fix the problem and I get the same error. If I give a path instead of a variable in Image.open, it does work correctly so I know the problem is trying to use a variable. Is there a way to do this that I'm missing?

2
  • What is the value of file_name when you get "IOError: cannot identify image file"? If the file name is "readme.txt" or something, it makes sense that PIL wouldn't be able to open it as an image. Additionally, does your source folder have any nested folders? For example, os.walk might identify lenna.jpg in the folder "source/pictures", and then Image.open(file_name) will fail, because it's only looking in the current active directory "source" for lenna.jpg, when it's actually in "source/pictures". Commented Jul 10, 2014 at 14:06
  • I completely forgot to mention that I'm testing this on a directory that has only jpg files in it to avoid any potential errors from non-image files. The code that Jamie posted also takes care of the subfolder problem. Commented Jul 10, 2014 at 14:31

1 Answer 1

2

You need to use this code instead:

img = Image.open(os.path.join(root, file_name))

If you have any non-image files in your directory hierarchy, then you will still have an error when you try to open them, but that is a legitimate error, so you could do something like:

try:
    img = Image.open(os.path.join(root, file_name))
except IOError:
    print "Error: %s does not appear to be a valid image" % (os.path.join(root, file_name))
else:
    exif = ...
Sign up to request clarification or add additional context in comments.

1 Comment

This worked perfectly. Thank you! I will add the error checking for non image files as well just to make sure I don't run into problems later on.

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.