• Python基础——使用with结构打开多个文件


    考虑如下的案例: 
    同时打开三个文件,文件行数一样,要求实现每个文件依次读取一行,然后输出,我们先来看比较容易想到的写法:

    with open(filename1, 'rb') as fp1:
        with open(filename2, 'rb') as fp2:
            with open(filename3, 'rb') as fp3:
                for i in fp1:
                    j = fp2.readline()
                    k = fp3.readline()
                    print(i, j, k)

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

    for i, j, k in fp1, fp2, fp3:
        print(i, j, k)

    但可使用强大的zip操作:

    for i, j, k in zip(fp1, fp2, fp3):
        print(i, j, k)

    这样层层的嵌套未免啰嗦,with结构支持一种更简洁的写法:

    with open(filename1, 'rb') as fp1, open(filename2, 'rb') as fp2, open(filename3, 'rb') as fp3:
        for i in fp1:
            j = fp2.readline()
            k = fp3.readline()
            print(i, j, k)

    或者使用更为优雅的写法,此时需要contextlib语法糖:

    from contextlib improt ExitStack
    with ExitStack() as stack:
        files = [stack.enter_context(open(fname)) for fname in [filename1, filename2, filename3]]
        for i, j, k in zip(files[0], files[1], files[2]):
            print(i, j, k)
  • 相关阅读:
    HDU 1540 Tunnel Warfare (线段树区间合并)
    P2258 子矩阵
    P5021 赛道修建
    P4084 [USACO17DEC]Barn Painting
    P3914 染色计数
    比赛用模板
    P3594 [POI2015]WIL-Wilcze doły
    P5022 旅行
    P3952 时间复杂度
    P3960 列队
  • 原文地址:https://www.cnblogs.com/dancesir/p/7804989.html
Copyright © 2020-2023  润新知