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

后端 未结 7 937
天涯浪人
天涯浪人 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 08:56

    For opening many files at once or for long file paths, it may be useful to break things up over multiple lines. From the Python Style Guide as suggested by @Sven Marnach in comments to another answer:

    with open('/path/to/InFile.ext', 'r') as file_1, \
         open('/path/to/OutFile.ext', 'w') as file_2:
        file_2.write(file_1.read())
    

提交回复
热议问题