Python with关键字,上下文管理器,@contextmanager文件操作示例

时间:2022-06-22 06:09:28

本文实例讲述了Python with关键字,上下文管理器,@contextmanager文件操作。分享给大家供大家参考,具体如下:

demo.py(with 打开文件):

?
1
2
3
4
# open 方法的返回值赋值给变量 f,当离开 with 代码块的时候,系统会自动调用 f.close() 方法
# with 的作用和使用 try/finally 语句是一样的。
with open("output.txt", "r") as f:
  f.write("XXXXX")

demo.py(with,上下文管理器):

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 自定义的MyFile类
# 实现了 __enter__() 和 __exit__() 方法的对象都可称之为上下文管理器
class MyFile():
  def __init__(self, filename, mode):
    self.filename = filename
    self.mode = mode
  def __enter__(self):
    print("entering")
    self.f = open(self.filename, self.mode)
    return self.f
  # with代码块执行完或者with中发生异常,就会自动执行__exit__方法。
  def __exit__(self, *args):
    print("will exit")
    self.f.close()
# 会自动调用MyFile对象的__enter__方法,并将返回值赋给f变量。
with MyFile('out.txt', 'w') as f:
  print("writing")
  f.write('hello, python')
  # 当with代码块执行结束,或出现异常时,会自动调用MyFile对象的__exit__方法。

demo.py(实现上下文管理器的另一种方式):

?
1
2
3
4
5
6
7
8
9
10
from contextlib import contextmanager
@contextmanager
def my_open(path, mode):
  f = open(path, mode)
  yield f
  f.close()
# 将my_open函数中yield后的变量值赋给f变量。
with my_open('out.txt', 'w') as f:
  f.write("XXXXX")
  # 当with代码块执行结束,或出现异常时,会自动执行yield后的代码。

希望本文所述对大家Python程序设计有所帮助。

原文链接:https://blog.csdn.net/houyanhua1/article/details/84744135