关于python中with 和 try 块的联合使用的问题
来源:互联网 发布:2017年做淘宝还赚钱吗 编辑:程序博客网 时间:2024/06/11 22:26
最近学习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 yamldef 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" %filenameload_conf('aa.yaml')print __author__ result is :there is an erroe when open and load aa.yamlJinming
下面这个是不理想的:
#!/usr/bin/python#coding:utf-8__author__ = 'Jinming'import yamldef 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" %filenameload_conf('aa.yaml')print __author__ result is :......there is an erroe when open and load aa.yaml后面的语句并没有执行
所以在看一下上面的结论,就应该差不多明白了
0 0
- 关于python中with 和 try 块的联合使用的问题
- 关于while true 循环中 try catch块的使用
- 关于try语句块中含有return的报错的问题
- 关于 Java 中 try、finally 语句块的分析
- 关于java中 try和finally return的问题
- try与finally块中return的问题
- try与finally块中return的问题
- 关于C#和MYSQL的联合使用
- 关于pvr和plist的联合使用
- 关于Handler和BroadcastReceiver的联合使用
- Java中try块的作用
- try...catch...finally中try块发生的事件顺序
- python 中with的使用
- Python中关于try/except/finally的基础用法
- python数据类型检验-set()的使用和try的使用
- MAG中关于数组和COMBO,LIST的联合使用例子(MAGList和MAGInputList)
- 关于try、catch、finally语句块中含有return语句的几点说明
- 关于try、catch、finally语句块中含有return语句的几点说明
- 【C++】 strtoull: 字符串转为unsigned long long
- 使用Alcatraz来管理Xcode插件
- 大数据多路归并排序
- No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional
- centos6.5中安装docker
- 关于python中with 和 try 块的联合使用的问题
- 使用VMware Converter调整虚拟磁盘文件大小
- 指针小谈.指针的值
- POJ-2431 Expedition
- MAC-pro搭建jsp开发环境(Yosemite 10.10.5 + eclipse 4.5.1 + jdk-8u60-macosx-x64 + apache-tomcat-8.0.27 2)
- CSS控制列表
- ssh免密码登陆
- Tiled地图文件分析
- 安装 Kali Linux 后需要做的 20 件事