with语句
with open('some.txt',"w") as f:
for i in f:
print i
自定义上下文管理器
实现函数enter和exit
class Diycontextor:
def __init__(self,name,mode):
self.name = name
self.mode = mode
def __enter__(self):
print "Hi enter here!!"
self.filehander = open(self.name,self.mode)
return self.filehander
def __exit__(self,*para):
print "Hi exit here"
self.filehander.close()
with Diycontextor('py_ana.py','r') as f:
for i in f:
print i
enter()返回一个对象。上下文管理器会使用这一对象作为as所指的变量
参考:
- http://kuanghy.github.io/2015/08/08/python-with
- http://www.cnblogs.com/vamei/archive/2012/11/23/2772445.html
出处:https://blog.csdn.net/reallocing1/article/details/64526895