python同时从不同文件夹读取文件


方法一:利用zip函数

  zip函数把两个或以上迭代器封装,平行遍历读取多个迭代器。

  例子:

for file1,flie2 in zip(file_dir1, file_dir2):
    #dong something

  缺点:迭代器长度如果不同,那么当最短的迭代器遍历完之后,就会提前停止。

  参考文章:python中的 zip函数详解

方法二:利用with读取文件

  例子1:

with open(file1) as f1, open(file2) as f2:
    # do something

  例子2(简洁版):

from contextlib import nested
with nested(open(file1), open(file2), open(file3)) as (f1, f2, f3):
    # do something

  参考文章:python同时读取多个文件