29
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

在这里,我试图打印目录(和子)中所有文件的大小。但我知道im在行的时候不在范围内im.sizeelse但是如果不使用orfinally块,我该怎么做。

显示以下错误:

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

3 回答 3

27

“其他”子句有什么问题?

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
于 2012-06-25T08:40:50.613 回答
4

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

try:
    im = Image.open(os.path.join(dirname, filename))
except IOError:
    print 'error opening file :: ' + os.path.join(dirname, filename)
    continue
于 2012-06-25T08:36:44.290 回答
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)

此外,;在 Python 中没有。

于 2012-06-25T08:36:16.053 回答