关于python中with 和 try 块的联合使用的问题

最近学习python,看到with的用法,感觉不用try except就ok,但是事实证明并不是这样,如果不用try except,with语句只是帮你关闭没有释放的资源,并且抛出异常,但是后面的语句是不能执行的,所以为了即能够输出我们自定义的错误信息,又能不影响后面代码的执行,必须还得使用try except 语句。但是此时又会问:那使用with ,还有啥用呢?其实还有有用的,不用担心资源没有关闭,并且代码也精简了不少。如果理解的有错误,还望各位给指正,非常感谢!

为了把问题说清楚,我打算用实例来描述,如果文字看不太懂,把实例运行一下,估计也能明白了

首先我们先来看这么一段代码:

notice:本地目录是没有aa.yaml这个文件的

下面这个是正确的代码:

<pre name="code" class="python">#!/usr/bin/python
#coding:utf-8

__author__ = 'Jinming'

import yaml

def load_conf(filename):
    '''this function is used to read the yaml files
       parm of  filname: the filename of yaml file that you want you load
    '''
    dict_conf = {}
    try:
        with open(filename) as yaml_file:
            dict_conf = yaml.load(yamml_file)
        return dict_conf
    except IOError:
        print "there is an erroe when open and load %s" %filename

load_conf('aa.yaml')

print __author__   

result is :

there is an erroe when open and load aa.yaml
Jinming

下面这个是不理想的:

#!/usr/bin/python
#coding:utf-8

__author__ = 'Jinming'

import yaml

def load_conf(filename):
    '''this function is used to read the yaml files
       parm of  filname: the filename of yaml file that you want you load
    '''
    dict_conf = {}

    with open(filename) as yaml_file:
        dict_conf = yaml.load(yamml_file)
    return dict_conf

    print "there is an erroe when open and load %s" %filename

load_conf('aa.yaml')

print __author__   

result is :
......
there is an erroe when open and load aa.yaml
后面的语句并没有执行

所以在看一下上面的结论,就应该差不多明白了

(0)

相关推荐