Open In App

Copy Contents of One File to Another File – Python

Last Updated : 21 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two text files, the task is to write a Python program to copy the contents of the first file into the second file. The text files which are going to be used are first.txt and second.txt:

Using File handling to read and append

We will open first.txt in ‘r’ mode and will read the contents of first.txt. After that, we will open second.txt in ‘a’ mode and will append the content of first.txt into second.txt.

Python
# open both files
with open('first.txt','r') as firstfile, open('second.txt','a') as secondfile:
    
    # read content from first file
    for line in firstfile:
             
             # append content to second file
             secondfile.write(line)

Output:

Explanation: The open(‘first.txt’, ‘r’) opens ‘first.txt’ in read mode, while open(‘second.txt’, ‘a’) opens ‘second.txt’ in append mode. The for loop reads each line from ‘first.txt’ and appends it to ‘second.txt’ using the write() function.

Lets explore some other methods to do the same.

Using File handling to read and write

We will open first.txt in ‘r’ mode and will read the contents of first.txt. After that, we will open second.txt in ‘w’ mode and will write the content of first.txt into second.txt.

Python
# open both files
with open('first.txt','r') as firstfile, open('second.txt','w') as secondfile:
    
    # read content from first file
    for line in firstfile:
             
             # write content to second file
             secondfile.write(line)

Output:

Explanation: The open(‘first.txt’, ‘r’) opens ‘first.txt’ in read mode, while open(‘second.txt’, ‘w’) opens ‘second.txt’ in write mode, overwriting any existing content. The for loop reads each line from ‘first.txt’ and writes it to ‘second.txt’ using the write() function.

Using shutil.copy() module

shutil.copy() method in Python is used to copy the content of the source file to destination file or directory. 

Python
# import module
import shutil

# use copyfile()
shutil.copyfile('first.txt','second.txt')

Output:

Explanation: shutil.copyfile(‘first.txt’, ‘second.txt’) function copies the contents of ‘first.txt’ to ‘second.txt’, replacing any existing content in ‘second.txt’. It performs a direct byte-for-byte copy and does not preserve metadata like file permissions.



Similar Reads