2010-05-17 89 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