Python Program to Copy a File

In this example, you will learn to copy the content of a file to another file using Python.

To understand this example, you should have the knowledge of the following Python programming topics:

Using shutil module

from shutil import copyfile
copyfile("/root/a.txt", "/root/b.txt")

The first parameter of copyfile() is the path of the source file and the second parameter is the path of the destination file. The content of the destination file is replaced with the content of the source file.

There are other methods copy()cop2(), and copyfileobj() which serve the same purpose with some metadata changes.

MethodPreserves PermissionsSupports Directory as DestinationCopies MetadataSupports file object
copy()YesYesNoNo
copyfile()NoNoNoNo
copy2()YesYesYesNo
copyfileobj()NoNoNoYes