Search code examples
pythonconcatenation

How can I concatenate all .txt files in a folder and separate all of them with a line?


I'm very new to using Python, and I suspect this is easier than I think, but I have a lot (more than 200) .txt files in a folder that I would like to concatenate in a single one.

The problem: I want each .txt file to be separated by a new line in this new file.

I'm on Mac, by the way.

I saw some options online that require a list of all files names. I just have a lot of them, and would like to save some time by doing it differently. Any idea?


Solution

  • As you would like to concatenate whole files you can read in the contents of one file in a single statement, and write it out in a single statement, like this:

    import glob
    import os
    
    
    def main():
        os.chdir('H:\\')
    
        with open('out.txt','w') as outfile:
            for fname in glob.glob('*.txt'):
                if fname == 'out.txt':
                    continue
                # print(fname)
                with open(fname, 'r') as infile:
                    txt = infile.readlines()
                    outfile.writelines(txt)
                    outfile.write('\n') # separator line
    
    
    if __name__ == '__main__':
        main()
    

    Using the with statement takes care of closing the file properly after the with-block is left, or even if the script crashes.