With 语句等于 try catch

With statement equals try catch

在阅读了一些论文后,我仍然无法理解 python 的 with 声明。这两个代码做同样的事情吗? withtry catch 做同样的事情吗?

try:
  a = A()
  #do something with a


with A() as a:
  #do something with a

不,with 语句是 "context manager"。可以这样想:

with open(filename, "w") as file:
    do stuff in file

现在,当上面的代码完成所有操作并且执行离开 with 语句时,文件将不再打开。

请看这个,解释的很好:https://jeffknupp.com/blog/2016/03/07/python-with-context-managers/