Variable scope and Try Catch in python

2019-03-23 01:43发布

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

3条回答
Animai°情兽
2楼-- · 2019-03-23 02:23

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
查看更多
冷血范
3楼-- · 2019-03-23 02:23

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
查看更多
混吃等死
4楼-- · 2019-03-23 02:28
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.

查看更多
登录 后发表回答