在Python中处理多个输入和输出文件

0 投票
1 回答
1813 浏览
提问于 2025-04-15 20:32

我需要打开多个文件(2个输入文件和2个输出文件),对输入文件中的每一行进行复杂的处理,然后把结果追加到这两个输出文件的末尾。目前我使用的方式是:

in_1 = open(input_1)
in_2 = open(input_2)
out_1 = open(output_1, "w")
out_2 = open(output_2, "w")

# Read one line from each 'in_' file
# Do many operations on the DNA sequences included in the input files
# Append one line to each 'out_' file

in_1.close()
in_2.close()
out_1.close()
out_2.close()

这些文件很大(每个文件可能接近1GB),所以我一个一个地读取这些输入文件。我觉得这样做可能不是很符合Python的风格。:) 那么使用下面这种方式会好吗?

with open("file1") as f1:
    with open("file2") as f2:
        with open("file3") as f3:
            with open("file4") as f4:
                    # Read one line from each 'in_' file
                    # Do many operations on the DNA sequences...
                    # Append one line to each 'out_' file

如果可以的话,我能否在避免高度缩进的代码(注释部分,可能本身也包含缩进的行)情况下做到这一点?除非像建议的那样,我事先使用适当定义的函数?谢谢你的见解!

1 个回答

5

contextlib.nested() 这个功能让你可以在一行代码里同时使用多个上下文管理器:

with contextlib.nested(open(...), open(...), ...) as (in_1, in_2, ...):
  ....

撰写回答