牛骨文教育服务平台(让学习变的简单)
博文笔记

Python中使用With打开多个文件

创建时间:2016-11-02 投稿人: 浏览次数:3123

转载地址:http://www.hustyx.com/python/119/

使用with打开文件的好处不多说,这里记录一下如果要打开多个文件,该怎么书写简捷的代码。

场景是同时打开三个文件,文件行数一样,程序实现每个文件依次读取一行,同时输出。 首先来一种比较容易想到的写法,如下一样嵌套:

with open("file1") as f1:
    with open("file2") as f2:
        with open("file3") as f3:
            for i in f1:
                j = f2.readline()
                k = f3.readline()
                print(i,j,k)

注意,这里只能对一个文件进行for循环读取,不能写成:

for i,j,k in f1,f2,f3:
    print(i,j,k)

这么多层缩进太恶心了,还是来一种简洁些的写法:

with open("file1") as f1, open("file2") as f2, open("file3") as f3:
    for i in f1:
        j = f2.readline()
        k = f3.readline()
        print(i,j,k)

还有一种优雅一点的写法:

from contextlib import nested

with nested(open("file1"), open("file2"), open("file3")) as (f1,f2,f3):
    for i in f1:
        j = f2.readline()
        k = f3.readline()
        print(i,j,k)
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。