Variable scope and Try Catch in python

33,587

Solution 1

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

Solution 2

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

Solution 3

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.

Share:
33,587
shahalpk
Author by

shahalpk

I make stuffs for the web and occasionally for pc

Updated on July 19, 2022

Comments

  • shahalpk
    shahalpk almost 2 years
    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