Python concatenate text files

后端 未结 12 1948
無奈伤痛
無奈伤痛 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:02

    If you have a lot of files in the directory then glob2 might be a better option to generate a list of filenames rather than writing them by hand.

    import glob2
    
    filenames = glob2.glob('*.txt')  # list of all .txt files in the directory
    
    with open('outfile.txt', 'w') as f:
        for file in filenames:
            with open(file) as infile:
                f.write(infile.read()+'\n')
    

提交回复
热议问题