关于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
后面的语句并没有执行 

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

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值