当前位置:网站首页>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)
边栏推荐
猜你喜欢
在CANoe中通过Panel面板控制Test Module 运行(初级)
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
颜值爆表,推荐两款JSON可视化工具,配合Swagger使用真香
Sichuan cloud education and double teacher model
Cmooc Internet + education
If someone asks you about the consistency of database cache, send this article directly to him
软件测试工程师必备之软技能:结构化思维
Installation de la pagode et déploiement du projet flask
CAPL 脚本打印函数 write ,writeEx ,writeLineEx ,writeToLog ,writeToLogEx ,writeDbgLevel 你真的分的清楚什么情况下用哪个吗?
MySQL实战优化高手02 为了执行SQL语句,你知道MySQL用了什么样的架构设计吗?
随机推荐
C杂讲 文件 初讲
Competition vscode Configuration Guide
美疾控中心:美国李斯特菌疫情暴发与冰激凌产品有关
嵌入式開發中的防禦性C語言編程
C miscellaneous shallow copy and deep copy
嵌入式开发中的防御性C语言编程
如何搭建接口自动化测试框架?
Keep these four requirements in mind when learning single chip microcomputer with zero foundation and avoid detours
在CANoe中通过Panel面板控制Test Module 运行(高级)
宝塔的安装和flask项目部署
C杂讲 浅拷贝 与 深拷贝
CAPL 脚本打印函数 write ,writeEx ,writeLineEx ,writeToLog ,writeToLogEx ,writeDbgLevel 你真的分的清楚什么情况下用哪个吗?
15 medical registration system_ [appointment registration]
A necessary soft skill for Software Test Engineers: structured thinking
Contest3145 - the 37th game of 2021 freshman individual training match_ B: Password
If someone asks you about the consistency of database cache, send this article directly to him
The governor of New Jersey signed seven bills to improve gun safety
MySQL实战优化高手06 生产经验:互联网公司的生产环境数据库是如何进行性能测试的?
Installation of pagoda and deployment of flask project
如何让shell脚本变成可执行文件