当前位置:网站首页>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)
边栏推荐
- 如何搭建接口自动化测试框架?
- docker MySQL解决时区问题
- Canoe CAPL file operation directory collection
- NLP routes and resources
- Safety notes
- 14 医疗挂号系统_【阿里云OSS、用户认证与就诊人】
- MySQL實戰優化高手04 借著更新語句在InnoDB存儲引擎中的執行流程,聊聊binlog是什麼?
- The replay block of canoe still needs to be combined with CAPL script to make it clear
- Several errors encountered when installing opencv
- MySQL实战优化高手12 Buffer Pool这个内存数据结构到底长个什么样子?
猜你喜欢

Carolyn Rosé博士的社交互通演讲记录
![13 medical registration system_ [wechat login]](/img/c9/05ad1fc86e02cf51a37c9331938b0a.jpg)
13 medical registration system_ [wechat login]

Defensive C language programming in embedded development

112 pages of mathematical knowledge sorting! Machine learning - a review of fundamentals of mathematics pptx

再有人问你数据库缓存一致性的问题,直接把这篇文章发给他

CANoe的数据回放(Replay Block),还是要结合CAPL脚本才能说的明白

MySQL combat optimization expert 03 uses a data update process to preliminarily understand the architecture design of InnoDB storage engine
![[NLP] bert4vec: a sentence vector generation tool based on pre training](/img/fd/8e5e1577b4a6ccc06e29350a1113ed.jpg)
[NLP] bert4vec: a sentence vector generation tool based on pre training

Control the operation of the test module through the panel in canoe (primary)

51单片机进修的一些感悟
随机推荐
Vh6501 Learning Series
If someone asks you about the consistency of database cache, send this article directly to him
四川云教和双师模式
Popularization of security knowledge - twelve moves to protect mobile phones from network attacks
嵌入式開發中的防禦性C語言編程
How can I take a shortcut to learn C language in college
嵌入式开发中的防御性C语言编程
Installation de la pagode et déploiement du projet flask
[CV] target detection: derivation of common terms and map evaluation indicators
16 medical registration system_ [order by appointment]
Programmation défensive en langage C dans le développement intégré
Can I learn PLC at the age of 33
CANoe的数据回放(Replay Block),还是要结合CAPL脚本才能说的明白
Retention policy of RMAN backup
NLP routes and resources
软件测试工程师发展规划路线
Hugo blog graphical writing tool -- QT practice
Some thoughts on the study of 51 single chip microcomputer
Canoe cannot automatically identify serial port number? Then encapsulate a DLL so that it must work
Regular expressions are actually very simple