可变范围和python中的Try Catch

时间:2012-06-25 08:33:55

标签: python variables try-catch scope python-imaging-library

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

这里我试图打印目录(和子)中所有文件的大小。但我知道imim.size行之后不在范围之内。但是,如果不使用elsefinally块,我该怎么做呢。

显示以下错误:

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

3 个答案:

答案 0 :(得分:21)

“else”条款有什么问题?

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

现在,由于您处于循环中,您还可以使用“继续”语句:

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

答案 1 :(得分:4)

如果您无法将文件作为图像打开,并且只想处理有效图像,那么在您的except块中包含continue语句,该语句将带您进入{{1}的下一次迭代循环。

for

答案 2 :(得分:2)

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)

此外,Python中没有;