Python concatenate text files

后端 未结 12 1957
無奈伤痛
無奈伤痛 2020-11-22 02:51

I have a list of 20 file names, like [\'file1.txt\', \'file2.txt\', ...]. I want to write a Python script to concatenate these files into a new file. I could op

12条回答
  •  不知归路
    2020-11-22 03:03

    def concatFiles():
        path = 'input/'
        files = os.listdir(path)
        for idx, infile in enumerate(files):
            print ("File #" + str(idx) + "  " + infile)
        concat = ''.join([open(path + f).read() for f in files])
        with open("output_concatFile.txt", "w") as fo:
            fo.write(path + concat)
    
    if __name__ == "__main__":
        concatFiles()
    

提交回复
热议问题