有时候在编写程序的时候有需求要同时打开多个文件,这几个文件可能是经由原来某个文件拆分,分别进行一些处理后希望合并,此时需要同时打开这些文件并读取。通常Python中打开文本使用的是with
语句,比如打开一个文件并读取每一行
with open(filename) as fp:
for line in fp:
# do something
为了同时读取多个文件,可以使用下面的代码
with open(filename1) as fp1, open(filename2) as fp2, open(filename3) as fp3:
for l1 in fp1:
l2 = fp2.readline()
l3 = fp3.readline()
# do something
稍微简介一点可以使用contextlib
中的nested
,有
from contextlib import nested
with nested(open(filename1), open(filename2), open(filename3)) as (fp1, fp2, fp3):
for l1 in fp1:
l2 = fp2.readline()
l3 = fp3.readline()
# do something