Python Program to Merge Two Files
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
How to Think About It
Algorithm
Code
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')
Dry Run
Let's trace merging file1.txt containing 'Hello\n' and file2.txt containing 'World\n'.
Open files
file1.txt opened for reading, file2.txt opened for reading, merged.txt opened for writing
Read file1.txt
Read content: 'Hello\n'
Read file2.txt
Read content: 'World\n'
Write to merged.txt
Write 'Hello\n' then 'World\n' into merged.txt
Close files
All files closed
| Step | Action | Content Written to merged.txt |
|---|---|---|
| 1 | Open files | |
| 2 | Read file1.txt | |
| 3 | Read file2.txt | |
| 4 | Write file1.txt content | Hello |
| 5 | Write file2.txt content | Hello 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
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')
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')
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Read all at once | O(n + m) | O(n + m) | Small to medium files, simple code |
| Line-by-line | O(n + m) | O(1) | Large files, memory efficient |
| fileinput module | O(n + m) | O(1) | Large files, easy iteration over multiple files |
with open() to handle files safely and avoid forgetting to close them.