Variable scope and Try Catch in python

Question:

import Image
import os
for dirname, dirs, files in os.walk("."):
    for filename in files:
        try:
            im = Image.open(os.path.join(dirname,filename))
        except IOError:
            print "error opening file :: "  + os.path.join(dirname,filename)
        print im.size

Here I’m trying to print the size of all the files in a directory (and sub). But I know im is outside the scope when in the line im.size. But how else do I do it without using else or finally blocks.

The following error is shown:

Traceback (most recent call last):
  File "batch.py", line 13, in <module>
    print im.size
NameError: name 'im' is not defined
Asked By: shahalpk

||

Answers:

import Image
import os
for dirname,dirs,files in os.walk("."):
    for filename in files:
        try:
            im = Image.open(os.path.join(dirname,filename))
            print im.size
        except IOError:
            print "error opening file :: "  + os.path.join(dirname,filename)

Also, no ; in Python.

Answered By: Burhan Khalid

If you can’t open the file as an image, and only want to work on valid images, then include a continue statement in your except block which will take you to the next iteration of your for loop.

try:
    im = Image.open(os.path.join(dirname, filename))
except IOError:
    print 'error opening file :: ' + os.path.join(dirname, filename)
    continue
Answered By: Christian Witts

What’s wrong with the “else” clause ?

for filename in files:
    try:
        im = Image.open(os.path.join(dirname,filename))
    except IOError, e:
        print "error opening file :: %s : %s" % (os.path.join(dirname,filename), e)
    else:
        print im.size

Now since you’re in a loop, you can also use a “continue” statement:

for filename in files:
    try:
        im = Image.open(os.path.join(dirname,filename))
    except IOError, e:
        print "error opening file :: %s : %s" % (os.path.join(dirname,filename), e)
        continue

    print im.size
Answered By: bruno desthuilliers