2015-12-20 57 views
4

这是代码Python的 '与' 命令

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建议(如果我理解正确的话),后者是真实的。不过,前者对我来说会更有意义。如果我错了,我错过了什么?

+1

它不等同于任一。如果'process'引发错误怎么办? 'with'不会在这里处理错误,但另外两个可以。 –

+1

@ajcr:既不尝试:......最后:'。第二节相同。 –

+0

我的错误。当它不在时,我不知何故读取“除了”。 –

回答

4

它相当于后者,因为直到open()成功返回,f没有任何价值,并且不应该关闭。

+0

'''会一直关闭你的文件。第二个例子如何做到这一点? – agconti

+0

@agconti如果'open()'失败,文件从不打开,所以也不需要关闭。 – poke

+1

@agconti如果'open()'产生一个异常,'f'甚至不会被初始化。不仅如此,没有理由关闭'f',但如果你尝试过,'f.close()'会引发'NameError:name'f'没有被定义'。 – zvone

5

按照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) 

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