Append Content of One Text File to Another Python (original) (raw)
Last Updated : 13 Jan, 2026
Given two text files, the task is to append the entire content of the second file (source) to the end of the first file (target) using Python.
**file1.txt

**file2.txt

After appending file2 -> file1:
geeksforgeeks
Using shutil.copyfileobj()
This method is the most efficient for large files. It copies data in chunks directly from one file to another.
Python `
import shutil
with open('file2.txt', 'r') as f2, open('file1.txt', 'a') as f1: shutil.copyfileobj(f2, f1)
`
**Output
geeksforgeeks
**Explanation:
- **open('file2.txt', 'r'): Opens source file in read mode
- **open('file1.txt', 'a'): Opens target file in append mode
- **shutil.copyfileobj(f2, f1): Copies content from file2 to file1 efficiently
Using File Object (read() + write())
This method reads the entire content of the source file at once using read() and appends it to the target file using write().
Python `
with open('file2.txt', 'r') as f2: data = f2.read()
with open('file1.txt', 'a') as f1: f1.write(data)
`
**Output
geeksforgeeks
**Explanation:
- **open('file2.txt', 'r'): Opens source file in read mode
- **f2.read(): Reads entire content of file2
- **open('file1.txt', 'a'): Opens target file in append mode
- **f1.write(data): Appends file2 content to file1
Using fileinput Module
This method is useful when processing multiple input files line by line, but it is less readable and rarely needed for simple appending.
Python `
import fileinput
with open('file1.txt', 'a') as f1: for line in fileinput.input('file2.txt'): f1.write(line)
`