可变范围并尝试在python中捕获 [英] Variable scope and Try Catch in python

查看:77
本文介绍了可变范围并尝试在python中捕获的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.size中时不在范围内.但是,如果不使用elsefinally块,该怎么办呢?

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.

显示以下错误:

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

推荐答案

"else"子句有什么问题?

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

现在,由于您处于循环状态,因此还可以使用"continue"语句:

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

这篇关于可变范围并尝试在python中捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆