2015-12-20 60 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塊之前。