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