2010-05-17 28 views

回答

16

你也可以這樣做:

from contextlib import nested 

with nested(open(spam), open(eggs)) as (f_spam, f_eggs): 
    # do something 

在Python 2.7和3.1+你不需要nested功能,因爲with支持的語法如下:

with open(spam) as f_spam, open(eggs) as f_eggs: 
    # do something 
+0

會怎麼做ü它在Python 3中? – Tshepang 2010-05-17 10:29:28

+3

'打開(垃圾郵件)作爲f_spam,打開(蛋)作爲f_eggs:'.................. 請參閱第四個項目符號在http:// docs。 python.org/release/3.1/whatsnew/3.1.html#other-language-changes – blokeley 2010-05-17 13:58:31

3
with open(spam,'r') as f_spam: 
    with open(eggs,'r') as f_bar: 
    #do stuff with each