&引用;加上;Python中要处理多个文件的语句
在这种情况下,如何使用该语句&引用;加上;Python中要处理多个文件的语句,python,Python,在这种情况下,如何使用该语句 f_spam = open(spam,'r') f_bar = open(eggs,'r') ... do something with these files ... f_spam.close() f_bar.close() 文件数可能大于两个 您还可以执行以下操作: with open(spam,'r') as f_spam: with open(eggs,'r') as f_bar: #do stuff with each from conte
f_spam = open(spam,'r')
f_bar = open(eggs,'r')
...
do something with these files
...
f_spam.close()
f_bar.close()
文件数可能大于两个 您还可以执行以下操作:
with open(spam,'r') as f_spam:
with open(eggs,'r') as f_bar:
#do stuff with each
from contextlib import nested
with nested(open(spam), open(eggs)) as (f_spam, f_eggs):
# do something
在Python 2.7和3.1+中,您不需要嵌套的函数,因为with
支持以下语法:
with open(spam) as f_spam, open(eggs) as f_eggs:
# do something
在Python3中,你会怎么做?将open(spam)作为f_spam,open(eggs)作为f_eggs:
。。。。。。。。。。。。。。。。。。看到第四个要点了吗?是的,谢谢这是我一直在寻找的