Python上下文管理器

  1. with语句
# with语句简化文件操作,出错也会关闭文件
with open('abc.txt','r',encoding='utf-8') as file:
    file_data = file.read()
    print(file_data)

  1. 自写文件管理器
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)

posted @ 2021-03-09 20:50  code-G  阅读(58)  评论(0编辑  收藏  举报