当前位置:网站首页>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 CAPL file operation directory collection
- Hugo blog graphical writing tool -- QT practice
- Safety notes
- CAPL脚本中关于相对路径/绝对路径操作的几个傻傻分不清的内置函数
- 零基础学习单片机切记这四点要求,少走弯路
- 华南技术栈CNN+Bilstm+Attention
- Listen to my advice and learn according to this embedded curriculum content and curriculum system
- Notes of Dr. Carolyn ROS é's social networking speech
- 如何搭建接口自动化测试框架?
- A new understanding of RMAN retention policy recovery window
猜你喜欢

AI的路线和资源

嵌入式开发比单片机要难很多?谈谈单片机和嵌入式开发设计经历

寶塔的安裝和flask項目部署

C杂讲 动态链表操作 再讲

CAPL 脚本打印函数 write ,writeEx ,writeLineEx ,writeToLog ,writeToLogEx ,writeDbgLevel 你真的分的清楚什么情况下用哪个吗?

Cmooc Internet + education

Carolyn Rosé博士的社交互通演讲记录

Defensive C language programming in embedded development

在CANoe中通过Panel面板控制Test Module 运行(高级)

13 医疗挂号系统_【 微信登录】
随机推荐
MySQL实战优化高手08 生产经验:在数据库的压测过程中,如何360度无死角观察机器性能?
[one click] it only takes 30s to build a blog with one click - QT graphical tool
15 medical registration system_ [appointment registration]
单片机实现模块化编程:思维+实例+系统教程(实用程度令人发指)
AI的路线和资源
[untitled]
CAPL script pair High level operation of INI configuration file
16 医疗挂号系统_【预约下单】
Popularization of security knowledge - twelve moves to protect mobile phones from network attacks
软件测试工程师发展规划路线
Configure system environment variables through bat script
Contrôle de l'exécution du module d'essai par panneau dans Canoe (primaire)
If someone asks you about the consistency of database cache, send this article directly to him
PR 2021 quick start tutorial, first understanding the Premiere Pro working interface
Several errors encountered when installing opencv
手把手教您怎么编写第一个单片机程序
Elk project monitoring platform deployment + deployment of detailed use (II)
Vscode common instructions
MySQL实战优化高手11 从数据的增删改开始讲起,回顾一下Buffer Pool在数据库里的地位
CANoe CAPL文件操作目录合集