How can I open multiple files using “with open” in Python?

后端 未结 7 965
天涯浪人
天涯浪人 2020-11-22 08:15

I want to change a couple of files at one time, iff I can write to all of them. I\'m wondering if I somehow can combine the multiple open calls with the

7条回答
  •  暖寄归人
    2020-11-22 09:05

    Nested with statements will do the same job, and in my opinion, are more straightforward to deal with.

    Let's say you have inFile.txt, and want to write it into two outFile's simultaneously.

    with open("inFile.txt", 'r') as fr:
        with open("outFile1.txt", 'w') as fw1:
            with open("outFile2.txt", 'w') as fw2:
                for line in fr.readlines():
                    fw1.writelines(line)
                    fw2.writelines(line)
    

    EDIT:

    I don't understand the reason of the downvote. I tested my code before publishing my answer, and it works as desired: It writes to all of outFile's, just as the question asks. No duplicate writing or failing to write. So I am really curious to know why my answer is considered to be wrong, suboptimal or anything like that.

提交回复
热议问题