当前位置:网站首页>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)
边栏推荐
- cmooc互联网+教育
- Jar runs with error no main manifest attribute
- 软件测试工程师必备之软技能:结构化思维
- Cooperative development in embedded -- function pointer
- Pointer learning
- 嵌入式開發中的防禦性C語言編程
- Function description of shell command parser
- MySQL Real Time Optimization Master 04 discute de ce qu'est binlog en mettant à jour le processus d'exécution des déclarations dans le moteur de stockage InnoDB.
- [one click] it only takes 30s to build a blog with one click - QT graphical tool
- 通过bat脚本配置系统环境变量
猜你喜欢
The programming ranking list came out in February. Is the result as you expected?
The replay block of canoe still needs to be combined with CAPL script to make it clear
13 medical registration system_ [wechat login]
Redis集群方案应该怎么做?都有哪些方案?
Embedded development is much more difficult than MCU? Talk about SCM and embedded development and design experience
Installation de la pagode et déploiement du projet flask
Teach you how to write the first MCU program hand in hand
单片机实现模块化编程:思维+实例+系统教程(实用程度令人发指)
16 medical registration system_ [order by appointment]
14 medical registration system_ [Alibaba cloud OSS, user authentication and patient]
随机推荐
四川云教和双师模式
What you have to know about network IO model
Zsh configuration file
好博客好资料记录链接
Combined search /dfs solution - leetcode daily question - number of 1020 enclaves
Compress decompress
在CANoe中通过Panel面板控制Test Module 运行(初级)
17 医疗挂号系统_【微信支付】
13 医疗挂号系统_【 微信登录】
Simple solution to phpjm encryption problem free phpjm decryption tool
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?
CDC: the outbreak of Listeria monocytogenes in the United States is related to ice cream products
Nc17 longest palindrome substring
Automation sequences of canoe simulation functions
MySQL实战优化高手09 生产经验:如何为生产环境中的数据库部署监控系统?
单片机如何从上电复位执行到main函数?
C miscellaneous two-way circular linked list
C miscellaneous dynamic linked list operation
oracle sys_ Context() function
Elk project monitoring platform deployment + deployment of detailed use (II)