分享

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

 LibraryPKU 2021-08-25

最近学习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

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多