代码:
1 # -*- coding:utf-8 -*- 2 # 普通版 如果写入的过程中出错 则不会释放资源 3 def m1(): 4 f = open("test.txt","w") 5 f.write("hello python") 6 f.close() 7 # 进阶版 8 def m2(): 9 f = open("test2.txt","w") 10 try: 11 f.write("hello python2") 12 except IOError: 13 print("oops error") 14 finally: 15 f.close() 16 # 高级 17 def m3(): 18 with open("test3.txt","w") as f: 19 f.write("hello python3") 20 m1() 21 m2() 22 m3() 23 24 # 上下文管理器 25 # 任何实现了 __enter__() 和 __exit__() 方法的对象都可称之为上下文管理器,上下文管理器对象可以使用 with 关键字。显然,文件(file)对象也实现了上下文管理器。 26 class File(object): 27 def __init__(self,filename,model): 28 self.filename = filename 29 self.model = model 30 31 def __enter__(self): 32 print("--enter--") 33 self.f = open(self.filename,self.model) 34 return self.f 35 36 def __exit__(self, *args): 37 print("--exit--") 38 self.f.close() 39 40 with File("test4.txt","w") as f: 41 f.write("hello python4") # 输出 --enter-- 42 # --exit - - 43 # 装饰器实现上下文管理器 44 from contextlib import contextmanager 45 46 @contextmanager 47 def my_open(path,model,encod): 48 f = open(path,model,encoding=encod) 49 yield f 50 f.close() 51 52 with my_open("test5.txt","w",‘utf-8‘) as f: 53 f.write("contextmanager实现上下文管理器")
原文地址:https://www.cnblogs.com/yifengs/p/11438457.html
时间: 2024-10-09 10:24:07