How to merge multiple files into a new file using Python?

PythonServer Side ProgrammingProgramming

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)
raja
Published on 26-Dec-2017 10:55:29
Advertisements