7
在这种情况下,我如何使用with语句?“With”语句在Python中有多个文件可处理
f_spam = open(spam,'r')
f_bar = open(eggs,'r')
...
do something with these files
...
f_spam.close()
f_bar.close()
文件编号可能大于2。
在这种情况下,我如何使用with语句?“With”语句在Python中有多个文件可处理
f_spam = open(spam,'r')
f_bar = open(eggs,'r')
...
do something with these files
...
f_spam.close()
f_bar.close()
文件编号可能大于2。
你也可以这样做:
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
with open(spam,'r') as f_spam:
with open(eggs,'r') as f_bar:
#do stuff with each
会怎么做ü它在Python 3中? – Tshepang 2010-05-17 10:29:28
'打开(垃圾邮件)作为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