当前位置:网站首页>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)
边栏推荐
- 竞赛vscode配置指南
- C杂讲 动态链表操作 再讲
- Popularization of security knowledge - twelve moves to protect mobile phones from network attacks
- 16 医疗挂号系统_【预约下单】
- CANoe下载地址以及CAN Demo 16的下载与激活,并附录所有CANoe软件版本
- 15 medical registration system_ [appointment registration]
- Compress decompress
- C miscellaneous dynamic linked list operation
- MySQL实战优化高手09 生产经验:如何为生产环境中的数据库部署监控系统?
- Several errors encountered when installing opencv
猜你喜欢
嵌入式开发比单片机要难很多?谈谈单片机和嵌入式开发设计经历
History of object recognition
The appearance is popular. Two JSON visualization tools are recommended for use with swagger. It's really fragrant
Programmation défensive en langage C dans le développement intégré
max-flow min-cut
PR 2021 quick start tutorial, first understanding the Premiere Pro working interface
解决在window中远程连接Linux下的MySQL
CAPL 脚本对.ini 配置文件的高阶操作
C miscellaneous lecture continued
C杂讲 文件 初讲
随机推荐
美新泽西州州长签署七项提高枪支安全的法案
Pointer learning
What you have to know about network IO model
A necessary soft skill for Software Test Engineers: structured thinking
Carolyn Rosé博士的社交互通演讲记录
cmooc互联网+教育
CANoe不能自动识别串口号?那就封装个DLL让它必须行
The 32-year-old fitness coach turned to a programmer and got an offer of 760000 a year. The experience of this older coder caused heated discussion
Jar runs with error no main manifest attribute
美疾控中心:美国李斯特菌疫情暴发与冰激凌产品有关
CANoe下载地址以及CAN Demo 16的下载与激活,并附录所有CANoe软件版本
Release of the sample chapter of "uncover the secrets of asp.net core 6 framework" [200 pages /5 chapters]
14 medical registration system_ [Alibaba cloud OSS, user authentication and patient]
Which is the better prospect for mechanical engineer or Electrical Engineer?
Southwest University: Hu hang - Analysis on learning behavior and learning effect
学习单片机对社会的帮助是很大的
零基础学习单片机切记这四点要求,少走弯路
51单片机进修的一些感悟
The appearance is popular. Two JSON visualization tools are recommended for use with swagger. It's really fragrant
The programming ranking list came out in February. Is the result as you expected?