27 July 2021

How to concatenate all the text files in a directory with Python?

 How to concatenate all the text files in a directory with Python?


https://stackoverflow.com/questions/13613336/python-concatenate-text-files

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')

No comments:

Post a Comment