CSDN话题挑战赛第2期
参赛话题:学习笔记

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 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.
上下文管理器协议:
__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__()方法的返回值正是输出的对象
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 666666666
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)
