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

后端 未结 7 794
天涯浪人
天涯浪人 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:04

    Late answer (8 yrs), but for someone looking to join multiple files into one, the following function may be of help:

    def multi_open(_list):
        out=""
        for x in _list:
            try:
                with open(x) as f:
                    out+=f.read()
            except:
                pass
                # print(f"Cannot open file {x}")
        return(out)
    
    fl = ["C:/bdlog.txt", "C:/Jts/tws.vmoptions", "C:/not.exist"]
    print(multi_open(fl))
    

    2018-10-23 19:18:11.361 PROFILE  [Stop Drivers] [1ms]
    2018-10-23 19:18:11.361 PROFILE  [Parental uninit] [0ms]
    ...
    # This file contains VM parameters for Trader Workstation.
    # Each parameter should be defined in a separate line and the
    ...
    

提交回复
热议问题