python-如果使用`with`语句打开文件,则调用`close()`是多余的

假设我有以下代码:

with open('somefile.txt') as my_file:
    # some processing
    my_file.close()

以上my_file.close()是否多余?

最佳答案

是的;此外,也不保证您的close()将始终被执行. (例如,如果发生异常).

with open('somefile.txt') as my_file:
    1/0 # raise Exception
    my_file.close() # Your close() call is never going to be called

但是始终执行with语句的__exit __()函数,因为它遵循try … except … finally模式.

The with statement is used to wrap the execution of a block with
methods defined by a context manager (see section With Statement
Context Managers). This allows common try…except…finally usage
patterns to be encapsulated for convenient reuse.

The context manager’s __exit__() method is invoked. If an exception
caused the suite to be exited, its type, value, and traceback are
passed as arguments to __exit__()

您可以在with语句之后使用closed检查文件是否已经关闭

>>> with open('somefile.txt') as f:
...     pass
>>> f.closed
# True

我的答案的来源:

> Understanding Python’s “with” statement