(更新时间)2021年3月29日 python基础知识(with语句和上下文管理器)
【摘要】
1. with语句的使用
with 语句的示例代码:
# 1、以写的方式打开文件
with open("1.txt", "w") as f:
# 2、读取文件内容
f.write("h...
1. with语句的使用
with 语句的示例代码:
# 1、以写的方式打开文件
with open("1.txt", "w") as f:
# 2、读取文件内容
f.write("hello world")
- 1
- 2
- 3
- 4
with 语句的这种写法,既简单又安全,并且 with 语句执行完成以后自动调用关闭文件操作,即使出现异常也会自动调用关闭文件操作。
2. 上下文管理器
自定义上下文管理器类,模拟文件操作:
class File(object):
# 初始化方法
def __init__(self, file_name, file_model):
# 定义变量保存文件名和打开模式
self.file_name = file_name
self.file_model = file_model
# 上文方法
def __enter__(self):
print("进入上文方法")
# 返回文件资源
self.file = open(self.file_name,self.file_model)
return self.file
# 下文方法
def __exit__(self, exc_type, exc_val, exc_tb):
print("进入下文方法")
self.file.close()
if __name__ == '__main__':
# 使用with管理文件
with File("1.txt", "r") as file:
file_data = file.read()
print(file_data)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
运行结果:
进入上文方法
hello world
进入下文方法
- 1
- 2
- 3
代码说明:
- __enter__表示上文方法,需要返回一个操作文件对象
- __exit__表示下文方法,with语句执行完成会自动执行,即使出现异常也会执行该方法。
3. 小结
- Python 提供了 with 语句用于简化资源释放的操作,使用 with
语句操作建立在上下文管理器(实现__enter__和__exit__)的基础上
文章来源: codeboy.blog.csdn.net,作者:愚公搬代码,版权归原作者所有,如需转载,请联系作者。
原文链接:codeboy.blog.csdn.net/article/details/115294981
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)