Python Program to Copy Files

« Previous Program Next Program »

Copy Files in Python

To copy files in python, you have to first import copyfile from shutil library (to use copyfile() function).

The copyfile() function copies the content of source file into destination file.

After importing copyfile from shutil library, you have to ask to enter name of the source and destination file to perform the copy file operation as shown in the program given here.

You may also like these two programs on file:

Python Programming Code to Copy Files

Following python program ask from user to enter name of source and destination file to copy the content of source file into destination file. After performing copy file operation, ask from the user, whether he/she want to display the content of the destination file or not. If he/she want to show the content, then just open the destination file and print all the content present inside it which is the content of the source file:

# Python Program - Copy Files

from shutil import copyfile;
print("Enter 'x' for exit.");
sourcefile = input("Enter source file name (copy from): ");
if sourcefile == 'x':
    destinationfile = input("Enter destination file name (copy to): ");
    copyfile(sourcefile, destinationfile);
    print("File copied successfully!");
    print("Want to display the content ? (y/n): ");
    check = input();
    if check == 'n':
        c = open(destinationfile, "r");

Here is the sample run of the above Python program to demonstrates how to copy the content of one file into another:

python copy files

Above is the initial output produced after running the program. Now let's copy all the contents of the file mynewfile.txt (created in write to file program) to the file codescracker.txt (mentioned in read a file program). To do this, first enter the file name as mynewfile.txt then press enter key and supply again another file name which will be destination file where the content of mynewfile.txt is going to copy, that is, the destination file will be codescracker.txt here and press enter key to do all this as shown in below sample run:

copy file program python

Now to see the content of the file codescracker.txt then supply y and press enter key as shown here:

python program copy file

Program Video with Compile and Run

Same Program in Other Languages

You may also like to learn or practice the same program in other popular programming languages:

« Previous Program Next Program »


Quick Links
Signup - Login - Give Online Test