How to Copy a File in Python (examples included)

In this short guide, I’ll show you how to copy a file in Python from one folder to another.

To start, here is a template that you can use to copy a file in Python using shutil.copyfile:

import shutil

original = r'original path where the file is currently stored\file name.file extension'
target = r'target path where the file will be copied\file name.file extension'

shutil.copyfile(original, target)

Let’s now see the steps to apply the above template in practice.

Steps to Copy a File in Python

Step 1: Capture the original path

To begin, capture the path where your file is currently stored.

For example, I stored a CSV file in a folder called Test_1:

C:\Users\Ron\Desktop\Test_1\products.csv

Where the CSV file name is ‘products‘ and the file extension is csv.

How to Copy a File in Python

Step 2: Capture the target path

Next, capture the target path where you’d like to copy the file.

In my case, the file will be copied into a folder called Test_2:

C:\Users\Ron\Desktop\Test_2\products.csv

Target Folder

Step 3: Copy the file in Python using shutil.copyfile

For the final step, use the following template to copy your file:

import shutil

original = r'original path where the file is currently stored\file name.file extension'
target = r'target path where the file will be copied\file name.file extension'

shutil.copyfile(original, target)

Make sure to place the ‘r‘ character before your paths to avoid the following error:

SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: truncated \UXXXXXXXX escape

In the context of our example, the complete code would look like this:

import shutil

original = r'C:\Users\Ron\Desktop\Test_1\products.csv'
target = r'C:\Users\Ron\Desktop\Test_2\products.csv'

shutil.copyfile(original, target)

Once I ran the code in Python, the ‘products‘ CSV file got copied into the Test_2 folder:

How to Copy a File in Python (examples included)

Alternatively, you could copy a file with a new name.

For instance, I copied the original CSV file (with the file name of ‘products‘) to the new location with a new file name (‘new_products‘):

import shutil

original = r'C:\Users\Ron\Desktop\Test_1\products.csv'
target = r'C:\Users\Ron\Desktop\Test_2\new_products.csv'

shutil.copyfile(original, target)

You’ll now see the new file name in the target location:

Folder in Windows

The same principles would apply for other file types. For instance, I now stored a JPG file called ‘image‘ under the Test_1 folder:

JPG file

The following code was then used to copy the image to the Test_2 folder:

import shutil

original = r'C:\Users\Ron\Desktop\Test_1\image.jpg'
target = r'C:\Users\Ron\Desktop\Test_2\image.jpg'

shutil.copyfile(original, target)

The JPG file will now appear in the Test_2 folder:

How to Copy a File in Python (examples included)