Computer >> Computer tutorials >  >> Programming >> Python

How to concatenate two files into a new file using Python?


To merge multiple files in a new file, you can simply read files and write them to a new file using loops.

For example

filenames = ['file1.txt', 'file2.txt', 'file3.txt']
with open('output_file', 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            outfile.write(infile.read())

If you have very big files, instead of writing them at once, you could write them line by line.

For example

filenames = ['file1.txt', 'file2.txt', 'file3.txt']
with open('output_file', 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            for line in infile:
                outfile.write(line)