这里写目录标题
一、open操作文件
f=open('1.txt','r',encoding='utf-8') res=f.readline() print(res) f.close() res=f.readline() print(res)
当使用open读取文件,关闭文件,再次读取文件时报异常
ValueError: I/O operation on closed file.
二、使用with启动文档句柄对象的上下文管理器
with open('1.txt','r',encoding='utf-8') as f1: res=f1.readline() print(res) res=f1.readline() print(res)
当使用with读取文件后,在with外部再次读取文件时也会报异常
ValueError: I/O operation on closed file.
三、with打开文件为何会自动关闭?
上下文管理器协议:
__enter__()
:进入上下文(with 操作对象时)
__exit__()
:退出上下文(with中的代码快执行完毕之后)
with是用来启动对象的上下文协议的,不是用来专门操作文件的
class MyOpen: def __enter__(self): return 'success' def __exit__(self, exc_type, exc_val, exc_tb): print('执行结束') obj=MyOpen() with obj as f: print(f)
四、自己实现一个类支持__enter__()和__exit__()方法
__enter__()
方法的返回值正是输出的对象
class MyOpen: def __init__(self,filename,mode,encoding='utf-8'): self.f=open(filename,mode,encoding=encoding) def __enter__(self): return self.f def __exit__(self, exc_type, exc_val, exc_tb): self.f.close() with MyOpen('1.txt','r',encoding='utf-8') as f: res=f.readline() print("res",res)
执行结果
res
五、基于pymysql实现一个操作数据库的类DBClass,实现上下文管理器协议,实现退出上下文时,自动关闭游标,断开连接
from pymysql import * class DBClass: def __init__(self, user, password, host, db, port, charset="utf8"): self.user = user self.password = password self.host = host self.db = db self.port = port self.charset = charset self.conn = connect(user=self.user, password=self.password, host=self.host, db=self.db, port=self.port, charset=self.charset) def __enter__(self): self.cur=self.conn.cursor() return self.cur def __exit__(self, exc_type, exc_val, exc_tb): self.cur.close() self.conn.close() if __name__ == '__main__': db=DBClass('root','root','127.0.0.1','ceshikaifa',3306)
今天的文章 python——上下文管理器with分享到此就结束了,感谢您的阅读。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/bian-cheng-ji-chu/89061.html