在Python中使用多个输入和输出文件

时间:2010-03-17 19:10:51

标签: file python

我需要打开多个文件(2个输入和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()

文件很大(每个都可能接近1Go,这就是我一次读取这些输入文件的原因。我猜这不是一种非常Pythonic的做事方式。:)会使用下面的表格好?

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 个答案:

答案 0 :(得分:5)

contextlib.nested()允许您在一个语句中链接多个上下文管理器:

with contextlib.nested(open(...), open(...), ...) as (in_1, in_2, ...):
  ....
相关问题