当前位置:网站首页>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)
边栏推荐
- C miscellaneous two-way circular linked list
- A necessary soft skill for Software Test Engineers: structured thinking
- [untitled]
- Constants and pointers
- The programming ranking list came out in February. Is the result as you expected?
- CANoe下载地址以及CAN Demo 16的下载与激活,并附录所有CANoe软件版本
- How can I take a shortcut to learn C language in college
- 美疾控中心:美国李斯特菌疫情暴发与冰激凌产品有关
- 零基础学习单片机切记这四点要求,少走弯路
- 软件测试工程师必备之软技能:结构化思维
猜你喜欢
C miscellaneous lecture continued
jar运行报错no main manifest attribute
Several silly built-in functions about relative path / absolute path operation in CAPL script
16 医疗挂号系统_【预约下单】
Keep these four requirements in mind when learning single chip microcomputer with zero foundation and avoid detours
再有人问你数据库缓存一致性的问题,直接把这篇文章发给他
实现微信公众号H5消息推送的超级详细步骤
A necessary soft skill for Software Test Engineers: structured thinking
max-flow min-cut
112 pages of mathematical knowledge sorting! Machine learning - a review of fundamentals of mathematics pptx
随机推荐
Programmation défensive en langage C dans le développement intégré
CAPL script pair High level operation of INI configuration file
[untitled]
How can I take a shortcut to learn C language in college
Preliminary introduction to C miscellaneous lecture document
MySQL實戰優化高手04 借著更新語句在InnoDB存儲引擎中的執行流程,聊聊binlog是什麼?
安装OpenCV时遇到的几种错误
docker MySQL解决时区问题
Contrôle de l'exécution du module d'essai par panneau dans Canoe (primaire)
Random notes
Canoe CAPL file operation directory collection
Sichuan cloud education and double teacher model
CANoe仿真功能之自动化序列(Automation Sequences )
Competition vscode Configuration Guide
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
oracle sys_ Context() function
Delayed note learning
C miscellaneous lecture continued
MySQL real battle optimization expert 08 production experience: how to observe the machine performance 360 degrees without dead angle in the process of database pressure test?
CAPL 脚本打印函数 write ,writeEx ,writeLineEx ,writeToLog ,writeToLogEx ,writeDbgLevel 你真的分的清楚什么情况下用哪个吗?