Q:

Copy contents from one file to another file in Python

belongs to collection: Python file handling programs

0

 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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Copy odd lines of one file to another file in Pyth... >>
<< Check if the record is present in the file using i...