简体   繁体   English

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

[英]Working with multiple input and output files in Python

I need to open multiple files (2 input and 2 output files), do complex manipulations on the lines from input files and then append results at the end of 2 output files. 我需要打开多个文件(2个输入文件和2个输出文件),对输入文件的行进行复杂的操作,然后将结果附加到2个输出文件的末尾。 I am currently using the following approach: 我目前正在使用以下方法:

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()

The files are huge (each potentially approaching 1Go, that is why I am reading through these input files one at a time. I am guessing that this is not a very Pythonic way to do things. :) Would using the following form good? 文件很大(每个文件可能接近1Go,这就是为什么我一次读取这些输入文件的原因。我猜想这不是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

If yes, could I do this while avoiding the highly indented code (commented part, which may itself contain indented lines. Unless, as suggested, I use appropriately defined functions beforehand)? 如果是,我是否可以这样做,同时避免使用高度缩进的代码(带注释的部分,其本身可能包含缩进的行。除非按照建议,否则我会事先使用适当定义的函数)? Thanks for the insights! 感谢您的见解!

contextlib.nested() allows you to chain multiple context managers in a single statement: contextlib.nested()允许您在单个语句中链接多个上下文管理器:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM