使用with打开文件的好处不多说,这里记录一下如果要打开多个文件,该怎么书写简捷的代码。
场景是同时打开三个文件,文件行数一样,程序实现每个文件依次读取一行,同时输出。 首先来一种比较容易想到的写法,如下一样嵌套:
with open('file1') as f1:
with open('file2') as f2:
with open('file3') as f3:
for i in f1:
j = f2.readline()
k = f3.readline()
print(i,j,k)
注意,这里只能对一个文件进行for循环读取,不能写成:
for i,j,k in f1,f2,f3:
print(i,j,k)
这么多层缩进太恶心了,还是来一种简洁些的写法:
with open('file1') as f1, open('file2') as f2, open('file3') as f3:
for i in f1:
j = f2.readline()
k = f3.readline()
print(i,j,k)
还有一种优雅一点的写法:
from contextlib import nested
with nested(open('file1'), open('file2'), open('file3')) as (f1,f2,f3):
for i in f1:
j = f2.readline()
k = f3.readline()
print(i,j,k)
网友评论