声明等于try catch

时间:2019-03-21 18:17:27

标签: python try-catch with-statement

在阅读了有关Python的with语句后,我仍然遇到一些麻烦。这两个代码是否做相同的事情? withtry catch做相同的事情吗?

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


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

1 个答案:

答案 0 :(得分:1)

否,with语句是“上下文管理器”。这样想:

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

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

请仔细阅读,它给出了一个很好的解释:https://jeffknupp.com/blog/2016/03/07/python-with-context-managers/