Posted in Python onJuly 16, 2019
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 同时读取多个文件的例子
- Author -
想做码农声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@