使用python读写文件,一开始我们用的是:
f = open('test.txt', 'r')
f.read()
最后一步是调用close()方法关闭文件
f.close()
如果打开报错IOError,那后面的close也不会执行,因此,我们可以使用try语句来容错:
try:
f = open('/path/to/file', 'r')
print(f.read())
finally:
if f:
f.close()
但每次这样写就太冗长了,于是有了一种优雅的写法:
with open('/path/to/file', 'r') as f:
print(f.read())
==========================with是如何工作的==============================
#!/usr/bin/env python
# with_example01.py
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 "sample:", sample
with 后面跟的语句get_sample()返回的是一个Sample对象
with要求Sample对象必须有一个__enter__()方法,一个__exit__()方法
当get_sample()返回一个Sample对象时,会调用Sample的__enter__()方法,__enter__()方法的返回值将赋给as后面的变量
在with后面的代码块抛出任何异常或者成功执行完成时,__exit__()方法被执行,将调用前面返回对象的__exit__()方法。
异常抛出时,与之关联的type,value和stack trace传给__exit__()方法,因此抛出的异常会被打印出来
所以上面这段代码的输出应该是
In __enter__() sample: Foo In __exit__()
参考文章: