0
0
PythonProgramBeginner · 2 min read

Python Program to Merge Two Files

You can merge two files in Python by opening both files in read mode, reading their contents, and then writing them into a new file using with open('file1.txt') as f1, open('file2.txt') as f2, open('merged.txt', 'w') as out: and writing out.write(f1.read() + f2.read()).
📋

Examples

Inputfile1.txt content: 'Hello\n' file2.txt content: 'World\n'
Outputmerged.txt content: 'Hello\nWorld\n'
Inputfile1.txt content: '123\n' file2.txt content: '456\n789\n'
Outputmerged.txt content: '123\n456\n789\n'
Inputfile1.txt content: '' file2.txt content: 'Only second file content\n'
Outputmerged.txt content: 'Only second file content\n'
🧠

How to Think About It

To merge two files, first open both files to read their contents. Then open a new file to write. Read all text from the first file, then read all text from the second file, and write both texts one after the other into the new file. This way, the new file contains all content from both files combined.
📐

Algorithm

1
Open the first file in read mode.
2
Open the second file in read mode.
3
Open a new file in write mode to store merged content.
4
Read the entire content of the first file.
5
Read the entire content of the second file.
6
Write the content of the first file to the new file.
7
Write the content of the second file to the new file.
8
Close all files.
💻

Code

python
with open('file1.txt', 'r') as f1, open('file2.txt', 'r') as f2, open('merged.txt', 'w') as out:
    out.write(f1.read())
    out.write(f2.read())

print('Files merged successfully into merged.txt')
Output
Files merged successfully into merged.txt
🔍

Dry Run

Let's trace merging file1.txt containing 'Hello\n' and file2.txt containing 'World\n'.

1

Open files

file1.txt opened for reading, file2.txt opened for reading, merged.txt opened for writing

2

Read file1.txt

Read content: 'Hello\n'

3

Read file2.txt

Read content: 'World\n'

4

Write to merged.txt

Write 'Hello\n' then 'World\n' into merged.txt

5

Close files

All files closed

StepActionContent Written to merged.txt
1Open files
2Read file1.txt
3Read file2.txt
4Write file1.txt contentHello
5Write file2.txt contentHello World
💡

Why This Works

Step 1: Open files safely

Using with open() ensures files are opened and closed properly without extra code.

Step 2: Read contents

Reading the entire content of each file with read() gets all text at once.

Step 3: Write merged content

Writing both contents one after another into the new file combines them in order.

🔄

Alternative Approaches

Line-by-line merging
python
with open('file1.txt') as f1, open('file2.txt') as f2, open('merged.txt', 'w') as out:
    for line in f1:
        out.write(line)
    for line in f2:
        out.write(line)

print('Files merged line by line')
This reads and writes line by line, useful for very large files to save memory.
Using fileinput module
python
import fileinput
with open('merged.txt', 'w') as out:
    for line in fileinput.input(['file1.txt', 'file2.txt']):
        out.write(line)

print('Files merged using fileinput')
This method merges files by iterating over all lines from both files seamlessly.

Complexity: O(n + m) time, O(n + m) space

Time Complexity

Reading and writing each file's content takes time proportional to the total size of both files, so O(n + m).

Space Complexity

Reading entire files at once uses memory proportional to their size, O(n + m). Line-by-line methods reduce memory use.

Which Approach is Fastest?

Reading all at once is simple and fast for small files; line-by-line or fileinput methods are better for large files to save memory.

ApproachTimeSpaceBest For
Read all at onceO(n + m)O(n + m)Small to medium files, simple code
Line-by-lineO(n + m)O(1)Large files, memory efficient
fileinput moduleO(n + m)O(1)Large files, easy iteration over multiple files
💡
Use with open() to handle files safely and avoid forgetting to close them.
⚠️
Forgetting to open the output file in write mode or not closing files properly.