ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Copy contents from one file to another file in Python

Here, we are going to learn how to copy contents of one file to another file in python in Python?
Submitted by Shivang Yadav, on February 12, 2021

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.

We will use the concepts of file handling in python and read and write the contents in the file.

Steps to copy contents from one file to another

  • Step 1: Take users the name of source and destination files.
  • 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.

Program to illustrate the solution of the problem

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 users 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.

Python file handling programs »

ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.