Python Program to Merge Two Files into a Third File (original) (raw)

Last Updated : 15 Jan, 2026

Merging files is a common file-handling task in Python. In this article, we’ll see how to merge two files into a third file using multiple approaches.

**Note: Make sure file1.txt and file2.txt exist in the same directory as your Python script.

Sample textfile:

**file1.txt

Python-file-handling-file1 **file2.txt Python-file-handling-file2

Using shutil.copyfileobj()

shutil.copyfileobj() efficiently copies content from one file object to another, without loading the entire file into memory. Ideal for large files.

Python `

with open('merged_file.txt', 'w') as outfile: for filename in ['file1.txt', 'file2.txt']: with open(filename, 'r') as infile: outfile.write(infile.read())
outfile.write('\n')

`

**Output (merged_file.txt)

This is the content from file1 .
Hello There.
This is in file1
Hello Geeks
This is in file2

**Explanation:

Using the os Module

This method uses basic file handling with the os module to read files line by line and write their contents into a single file. It is memory-efficient and suitable for large files.

Python `

with open('merged_file.txt', 'w') as outfile: for filename in ['file1.txt', 'file2.txt']: with open(filename, 'r') as infile: content = infile.read() outfile.write(content) if not content.endswith('\n'): outfile.write('\n')

`

**Output

This is the content from file1 .
Hello There.
This is in file1
Hello Geeks
This is in file2

**Explanation:

Using a For Loop

This method merges files by looping through a list of filenames and writing their contents to a new file. It is simple, readable, and beginner-friendly, making it suitable for small to medium-sized files.

Python `

filenames = ['file1.txt', 'file2.txt']

with open('file3.txt', 'w') as outfile: for name in filenames: with open(name) as infile: outfile.write(infile.read()) outfile.write("\n")

`

**Output

This is the content from file1.
Hello There.
This is in file1
Hello Geeks
This is in file2

**Explanation:

Naive Approach

This method reads the entire contents of both files into strings, concatenates them, and writes the combined string to a new file.

Python `

with open('file1.txt') as fp: data1 = fp.read()

with open('file2.txt') as fp: data2 = fp.read()

with open('file3.txt', 'w') as fp: fp.write(data1 + "\n" + data2)

`

**Output

This is the content from file1.
Hello There.
This is in file1
Hello Geeks
This is in file2

**Explanation: