python 技巧 文件

【小记】Python更加优雅的打开多个文件.md

简单记录

systemime
2021-05-10
1 min

with打开多个文件时,如果文件多,要么多层嵌套,要么一行写多个as,使用contextlib更优雅的打开多个文件

# Python2版本代码如下

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

# Python3版本代码如下

from contextlib import ExitStack
with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in ["1.txt", "2.txt", "3.txt"]]
    
    # eg.1
    for i, j, k in zip(files[0], files[1], files[2]):
        print(i, j, k)

    # eg.2
    for f in files:
        print(f.read())

# 封装为一个工具类

虽然貌似没啥鸟用 2233

# 苦逼加班,等两天再更新,需要的可评论

# 最近热了,歇会吧

上次编辑于: 5/15/2021, 2:22:50 AM