考虑如下的案例:
同时打开三个文件,文件行数一样,要求实现每个文件依次读取一行,然后输出,我们先来看比较容易想到的写法:
with open(filename1, 'rb') as fp1: with open(filename2, 'rb') as fp2: with open(filename3, 'rb') as fp3: for i in fp1: j = fp2.readline() k = fp3.readline() print(i, j, k)
注意这里只能对单个文件进行for循环读取,不能写成:
for i, j, k in fp1, fp2, fp3: print(i, j, k)
但可使用强大的zip操作:
for i, j, k in zip(fp1, fp2, fp3): print(i, j, k)
这样层层的嵌套未免啰嗦,with结构支持一种更简洁的写法:
with open(filename1, 'rb') as fp1, open(filename2, 'rb') as fp2, open(filename3, 'rb') as fp3: for i in fp1: j = fp2.readline() k = fp3.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)