python 同时读取多个文件的例子
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
以上这篇python 同时读取多个文件的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。