Skip to content
Related Articles

Related Articles

Python – Copy contents of one file to another file
  • Last Updated : 17 Dec, 2020

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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



filter_none

edit
close

play_arrow

link
brightness_4
code

# 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:
               
             # write content to second file
             secondfile.write(line)

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:


Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :