有時(shí)候在編寫(xiě)程序的時(shí)候有需求要同時(shí)打開(kāi)多個(gè)文件,這幾個(gè)文件可能是經(jīng)由原來(lái)某個(gè)文件拆分,分別進(jìn)行一些處理后希望合并婿牍,此時(shí)需要同時(shí)打開(kāi)這些文件并讀取。通常Python中打開(kāi)文本使用的是with
語(yǔ)句惩歉,比如打開(kāi)一個(gè)文件并讀取每一行
with open(filename) as fp:
for line in fp:
# do something
為了同時(shí)讀取多個(gè)文件等脂,可以使用下面的代碼
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
稍微簡(jiǎn)介一點(diǎn)可以使用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