包含 Python 中的文件的上下icode9文管理器


上下文管理器是什么?
它是一个在上下文开始和结束时通知实现两种魔法方法和任何其他方法的对象。__enter____exit__
例如,当上下文管理器结束时,对象文件将关闭。
withopen('test_ch30.txt','w+')asfile:
file.write('Blewthelidofurlife')
#theopenfilehasautomaticllybeenclossed
上下文管理器通常用于阅读和写入文件,以帮助节省系统内存,并通过保留每个过程的资源来改进资源管理。
打开文件using确保文件描述符自动关闭。with
Howstatment如何实现上下文管理器?with
1-当一个对象被调用时,
解释器调用该方法
调用和执行
执行过程所需的设置代码。with__eneter__with
2-当状态结束时,解释器调用该方法。with__exit__
插图:
可选文字
实现contect管理器需要什么?
classContextManager(object):
"""docstringforContextManager"""
def__init__(self):
pass
def__enter__(self):
print("__enter__()")
#optionalyreturnanobj
return"aninstance"
def__exit__(self,exc_type,exc_val,traceback):
print("__exit__with",exc_valifexc_valelse'nope')
withContextManager()ase:
print("isa",e)
多个上下文管理器
withopen('test_ch30.txt')asinput_file,open('test_ch77.txt','w')asoutput_file:
#dosomethingwithbothfiles.
#e.g.copythecontentsofinput_fileintooutput_file
forlineininput_file:
output_file.write(line+'
')
#Ithasthesameeffectasnestingcontextmanagers:
withopen('test_ch30.txt')asinput_file:
withopen('test_ch77.txt','w')asoutput_file:
forlineininput_file:
output_file.write(line+'
')
管理资源
classFile():
def__init__(self,filename,mode):
self.filename=filename
self.mode=mode
def__enter__(self):
self.open_file=open(self.filename,self.mode)
returnself.open_file
def__exit__(self,*args):
self.open_file.close()
for_inrange(10000):
withFile('test_ch30.txt','w')asf:
f.write('foo')
管理文件类别如下。
ManageFile遵循/遵守上下文管理器协议,支持类别with语句代码链接

本站声明:
1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;

2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;

3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;

4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;

5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/293820.html

(0)
上一篇 2022年11月27日
下一篇 2022年11月27日

相关推荐

发表回复

登录后才能评论