Python 'with' 命令

Python 'with' command

是这个代码吗

with open(myfile) as f:
    data = f.read()
    process(data)

相当于这个

try:
    f = open(myfile)
    data = f.read()
    process(f)
finally:
    f.close()

还是下一个?

f = open(myfile)
try:
    data = f.read()
    process(f)
finally:
    f.close()

这篇文章:http://effbot.org/zone/python-with-statement.htm 表明(如果我理解正确的话)后者是正确的。但是,前者对我来说更有意义。如果我错了,我错过了什么?

等同于后一个,因为直到open()成功returns,f才没有价值,不应该被关闭。

根据 documentation:

A new statement is proposed with the syntax:

with EXPR as VAR:
    BLOCK

The translation of the above statement is:

mgr = (EXPR)
exit = type(mgr).__exit__  # Not calling it yet
value = type(mgr).__enter__(mgr)
exc = True
try:
    try:
        VAR = value  # Only if "as VAR" is present
        BLOCK
    except:
        # The exceptional case is handled here
        exc = False
        if not exit(mgr, *sys.exc_info()):
            raise
        # The exception is swallowed if exit() returns true
finally:
    # The normal and non-local-goto cases are handled here
    if exc:
        exit(mgr, None, None, None)

这是您的 second 代码片段的扩展版本。初始化在 try ... finaly 块之前进行。