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

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:

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:

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)

`