簡體   English   中英

在Python中使用多個輸入和輸出文件

[英]Working with multiple input and output files in 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,這就是為什么我一次讀取這些輸入文件的原因。我猜想這不是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

如果是,我是否可以這樣做,同時避免使用高度縮進的代碼(帶注釋的部分,其本身可能包含縮進的行。除非按照建議,否則我會事先使用適當定義的函數)? 感謝您的見解!

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