with、上下文管理器
with open(文件) as f: pass
open方法的返回值赋值给变量f,当离开with代码块的时候,系统会自动调用f.close()方法,with的作用和使用try/finally语句是一样的。
上下文管理器:
任何实现了__enter__()和__exit__()方法的对象都可称为上下文管理器。
1 class File(): 2 3 def __init__(self, filename, mode): 4 self.filename = filename 5 self.mode = mode 6 7 def __enter(self): 8 print("entering") 9 self.f = open(self.filename, self.mode) 10 return self.f 11 12 def __exit(self, *args): 13 print("will exit") 14 self.f.close() 15 16 17 with File('测试.txt', 'w') as f: 18 print("writing") 19 f.write('hello ,python')
实现上下文管理器的另外方式:
1 from contextlib import contextmanager 2 3 @contextmanager 4 def my_open(path, mode): 5 f = open(path, mode) 6 yield f 7 f.close() 8 9 10 with my_open('测试.txt', 'w') as f: 11 f.write('hello,world')