DarkKnight4251
DarkKnight4251

Reputation: 53

How can I use a variable instead of a path to open an image file using PIL in Python?

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?

Upvotes: 0

Views: 6299

Answers (1)

Jamie Cockburn
Jamie Cockburn

Reputation: 7555

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 = ...

Upvotes: 2

Related Questions