Copy files in Python

Next we will show you some examples of how to copy files in Python with the shutil module.

» More Python Examples

Copy files with copyfile

To copy files, we use the copyfile function specifying the source and destination file path as arguments.

Note that the destination folder “subfolder” must exist.

import shutil

# geekole.com

source = "/home/geekole/Documents/python/files/file1.txt"
destination = "/home/geekole/Documents/python/files/subfolder/file1.txt"
shutil.copyfile(source, destination)

It will copy the file “file1.txt” to the path of “subFolder”.

Copy files in Python

With copy

The copy function is very similar to copyfile, but in addition, it will copy the permissions on the file, which is especially tricky in other languages.

import shutil

# geekole.com

source = "/home/geekole/Documents/python/files/file1.txt"
destination = "/home/geekole/Documents/python/files/subfolder/file1.txt"
shutil.copy(source, destination)

If we run the example we will see that the file “file1.txt” with read and write permissions is copied with the same permissions in “subfolder”.

Copy files in Python

We hope this example of copy files in python will help you.