In this tutorial, you will learn how to copy a file using Python from a directory to another directory, or if you’re on Windows, then from a Folder to another Folder.
shutil.copyfile
is a tool that is often used to copy a file in Python, below is an example of it’s usage, you can read more about it on the Python docs:
import shutil
# the source file
original = '/path/to/the/file.extension'
# the destination file
target = '/path/to/the/new/destination/newname.extension'
# perform the copy
shutil.copyfile(original, target)
Now let’s break this down and understand what happens…
What are the steps to Copy a File in Python
Step 1: Get the original path of the file
We need to know where the current file is.
In my case, it was a file called catalogue.csv
stored in the following location: /Users/ao/Documents/Shared
.
Step 2: Determine the target path
Next thing to do is find the location that we will set as the destination.
In our case, it is another folder/directory called backup
and can be found locally here: /Users/ao/Documents/Shared/backup
Step 3: Perform the Copy of the file in Python using shutil.copyfile
We can now populate our script with the paths we collected from before.
import shutil
# the source file
original = '/Users/ao/Documents/Shared/catalogue.csv'
# the destination file
target = '/Users/ao/Documents/Shared/backup/catalogue_backup.csv'
# perform the copy
shutil.copyfile(original, target)
It is often advised to place an r
in front of your paths to avoid the following error:
SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: truncated \UXXXXXXXX escape
Let’s do that now before running the script:
import shutil
# the source file
original = r'/Users/ao/Documents/Shared/catalogue.csv'
# the destination file
target = r'/Users/ao/Documents/Shared/backup/catalogue_backup.csv'
# perform the copy
shutil.copyfile(original, target)
Now that we have run our script, we can see that the file has been copied as expected.