当前位置:网站首页>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杂讲 文件 初讲
- Control the operation of the test module through the panel in canoe (primary)
- Programmation défensive en langage C dans le développement intégré
- The governor of New Jersey signed seven bills to improve gun safety
- Contrôle de l'exécution du module d'essai par panneau dans Canoe (primaire)
- MySQL实战优化高手06 生产经验:互联网公司的生产环境数据库是如何进行性能测试的?
- Installation de la pagode et déploiement du projet flask
- Tianmu MVC audit II
- Southwest University: Hu hang - Analysis on learning behavior and learning effect
- flask运维脚本(长时间运行)
猜你喜欢

宝塔的安装和flask项目部署

C杂讲 文件 初讲

15 医疗挂号系统_【预约挂号】

Contest3145 - the 37th game of 2021 freshman individual training match_ C: Tour guide

South China Technology stack cnn+bilstm+attention
![16 medical registration system_ [order by appointment]](/img/7f/d94ac2b3398bf123bc97d44499bb42.png)
16 medical registration system_ [order by appointment]

MySQL实战优化高手03 用一次数据更新流程,初步了解InnoDB存储引擎的架构设计

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

Release of the sample chapter of "uncover the secrets of asp.net core 6 framework" [200 pages /5 chapters]

How to make shell script executable
随机推荐
Installation of pagoda and deployment of flask project
MySQL实战优化高手06 生产经验:互联网公司的生产环境数据库是如何进行性能测试的?
51单片机进修的一些感悟
MySQL实战优化高手02 为了执行SQL语句,你知道MySQL用了什么样的架构设计吗?
C杂讲 文件 初讲
在CANoe中通過Panel面板控制Test Module 運行(初級)
Random notes
Why is 51+ assembly in college SCM class? Why not come directly to STM32
单片机如何从上电复位执行到main函数?
oracle sys_ Context() function
14 医疗挂号系统_【阿里云OSS、用户认证与就诊人】
MySQL ERROR 1040: Too many connections
A new understanding of RMAN retention policy recovery window
MySQL實戰優化高手08 生產經驗:在數據庫的壓測過程中,如何360度無死角觀察機器性能?
C杂讲 文件 续讲
VH6501学习系列文章
Teach you how to write the first MCU program hand in hand
[NLP] bert4vec: a sentence vector generation tool based on pre training
简单解决phpjm加密问题 免费phpjm解密工具
CAPL脚本中关于相对路径/绝对路径操作的几个傻傻分不清的内置函数