Python上下文管理器
- with语句
# with语句简化文件操作,出错也会关闭文件
with open('abc.txt','r',encoding='utf-8') as file:
file_data = file.read()
print(file_data)
- 自写文件管理器
class File(object):
def __init__(self,file_name,file_mode):
self.file_name = file_name
self.file_mode = file_mode
def __enter__(self):
self.file = open(self.file_name,self.file_mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
print('over')
self.file.close()
with File('abc.txt','rb') as file:
file_data = file.read()
print(file_data)