Sunday, October 5, 2025
HomeLanguagesPython – Copy contents of one file to another file

Python – Copy contents of one file to another file

Given two text files, the task is to write a Python program to copy contents of the first file into the second file.

The text files which are going to be used are second.txt and first.txt:

Method #1: 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.

Example:

Python3




# 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:

Method #2: 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.

Example:

Python3




# 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:

Method #3: Using shutil.copy() module

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

Example:

Python3




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


Output:

RELATED ARTICLES

Most Popular

Dominic
32337 POSTS0 COMMENTS
Milvus
86 POSTS0 COMMENTS
Nango Kala
6706 POSTS0 COMMENTS
Nicole Veronica
11870 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11934 POSTS0 COMMENTS
Shaida Kate Naidoo
6821 POSTS0 COMMENTS
Ted Musemwa
7086 POSTS0 COMMENTS
Thapelo Manthata
6779 POSTS0 COMMENTS
Umr Jansen
6778 POSTS0 COMMENTS