python with
来源:互联网 发布:怎样做网络代理 编辑:程序博客网 时间:2024/06/10 12:55
file = open(filename)data = file.read()file.close()
有两个问题需要注意
- 忘记关闭文件句柄
- 文件读取出现异常,没有进行任何处理
so,
try: file = open(filename)except: print 'error' exit(-1)try: data = file.read()except: passfinally: file.close()
还有一种写法是:
try: file = open(filename) data = file.read()except: passfinally: file.close()
个人感觉第一个方法比较好。
采用with的方法:
with open(filename) as file: data = file.read()
python 处理with的基本思想是,with所求值的对象必须有一个_enter_() 方法 和 _exit__() 方法,紧跟with后面的语句被求值后返回对象的_enter_()方法被调用,这个方法的返回值被赋值给as后面的变量。当with后面的代码块全部执行完之后,将调用_exit()方法。
class sample: def __enter__(self): print 'in __enter__' return 'Foo' def __exit__(self, type, value, trace): print 'in __exit__'def get_sample(): return sample()with get_sample() as sample: print 'simple', sample
class sample: def __enter__(self): print 'in enter' return self def __exit__(self, exc_type, exc_val, exc_tb): print 'type', exc_type print 'val', exc_val print 'tb', exc_tb def do_something(self): bar = 1 return bar + 10with sample() as f: print f.do_something()
resuklt:
in enter11type Noneval Nonetb NoneProcess finished with exit code 0
0 0
- python with
- Python with
- python with
- Python With
- python with
- Python With
- python with
- python with
- python~with
- python with
- Python with
- [Python]Apache with Mod_python
- Java with Python
- 【LeetCode with Python】 Permutations
- Starting Out with Python
- XML Processing with Python
- python with...as...用法
- python with用法
- MySQL中利用log file 和position来复制
- Gradle学习记录
- python练习册3
- EBPY0106是什么意思
- iOS开发 自定义NSOPeration
- python with
- mongodb学习笔记
- Android编译系统介绍
- 使用Setup Factory 制作安装包的一般过程
- LeetCode 374:Guess Number Higher or Lower
- UITextAlignmentCenter' is deprecated: first deprecated in iOS 6.0 UITextAlignmentCenter
- 解决ListVeiw点击事件失效问题
- 如何使用爬虫采集58招聘信息
- GetWindowText()有关问题解答——VS2012