当前位置:网站首页>Implement context manager through with

Implement context manager through with

2022-07-06 10:09:00 chuntian_ tester

with open() as f: Inside the method is actually right open() Function is encapsulated twice , Internally implemented __enter__ Methods and __exit__ Method .

We can also achieve this by ourselves 2 There are three methods to customize the context manager of the implementation file . 

#  Use with Implement a custom context manager 
class MyOpen(object):
    """
     Implement file operation context manager 
     Must be realized __enter__ Methods and __exit__ Method 
    with open('./user_info.txt','r',encoding='utf8') as f:
        content = f.read()
    """

    def __init__(self, file_name, open_type, encoding='utf8'):
        """ adopt init Method to receive parameters such as incoming files """
        self.file_name = file_name
        self.open_type = open_type
        self.encoding = encoding

    def __enter__(self):
        """ Customize open The way , Use with Keyword will automatically trigger this __enter__ Method """
        self.f = open(self.file_name, self.open_type, encoding=self.encoding)
        return self.f  #  Back here self.f Object will be assigned to "with open() as f" Medium f

    def __exit__(self, exc_type, exc_val, exc_tb):
        """ When with After the code in is executed , Will automatically trigger __exit__ Method , therefore , Close the file here """
        self.f.close()
        print(f' file "{self.file_name}" closed !')


if __name__ == '__main__':
    """
            w       Open... In writing ( Will overwrite the original file )
            r       Open as read-only 
            a       Open in append mode ( Append the data to be written to the end of the original file , Do not overwrite the original file )
            b       Open as binary 
            r+   w+  a+   All open in a read-write way 
            rb   Open in binary read mode 
            wb   Open in binary 
            ab   Open in binary append mode 
            rb+  wb+  ab+   Open in binary read-write mode ·
    """
    with MyOpen('./user_info.txt', 'a+') as f:
        f.write(" Xiaochuntian is so cute ....\n" )
    with MyOpen('./user_info.txt', 'r') as f:
        content = f.readlines()
        for line in content:
            print(line)

 

原网站

版权声明
本文为[chuntian_ tester]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131728483816.html