Copy contents from one file to another file in Python

Python | Copy contents from one file to another file: In this tutorial, we will learn how to copy the contents of one file to another file. Learn with the help of examples. By Shivang Yadav Last updated : July 05, 2023

Problem Statement

Python program to copy contents of one file to another file using file Handling.

Problem Description

We need to copy all data from one file to another file. The names of both files are provided by the user as input. If the destination file is not present create a new one.

Copy contents from one file to another file

To copy contents from one file to another file, we will use the concepts of file handling in python and read and write the contents in the file. The steps to copy contents from one file to another file are as follows,

  • Step 1: Take inputs of the name of source and destination files from the user.
  • Step 2: If the source there is a source file then copy the contents of source file to the destination file.
  • Step 3: If the destination file doesn't exist, create a new one.

Python program to copy contents from one file to another file

sfile=input("Enter Source File:")

try:
    sf=open(sfile,"rb")

    tfile = input("Enter Target File:")
    tf=open(tfile,"wb")

    tf.write(sf.read())

    sf.close()
    tf.close()
    print("File Copied...")
except FileNotFoundError as e:
    print(e)

Output

Enter Source File:data.dat
Enter Target File:newdata.dat
File Copied...

Files :
    data.dat
    10032,John Doe,45000
    10323,Ram,50000

    newData.dat 
    10032,John Doe,45000
    10323,Ram,50000

Here, we have asked user for inputs of file name for the source and destination. After the user has provided valid name of source file, we have copied its contents to the destination file (We first opened the source file using the File's open() method in read mode (rb, here b for binary format), opened the target file in the write mode (wb), and read the data using the File's read() method and wrote this data to the target file using the File's write() method).

Python file handling programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.