同时打开三个文件,文件行数一样,要求实现每个文件依次读取一行,然后输出,我们先来看比较容易想到的写法:

with open(filename1, 'rb') as f1:
with open(filename2, 'rb') as f2:
with open(filename3, 'rb') 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)

但可使用强大的zip操作:

for i, j, k in zip(f1, f2, f3):
print(i, j, k)

这样层层的嵌套未免啰嗦,with结构支持一种更简洁的写法:

with open(filename1, 'rb') as f1, open(filename2, 'rb') as f2, open(filename3, 'rb') as f3:
for i in f1:
j = f2.readline()
k = f3.readline()
print(i, j, k)

或者使用更为优雅的写法,此时需要contextlib语法糖:

from contextlib improt ExitStack
with ExitStack() as stack:
files = [stack.enter_context(open(fname)) for fname in [filename1, filename2, filename3]]
for i, j, k in zip(files[0], files[1], files[2]):
print(i, j, k)
05-28 22:25