How to copy files in Python?

Better Stack Team
Updated on January 26, 2023

To copy a file in Python, you can use the shutil module. Here is an example of how you can use the shutil.copy() function to copy a file:

import shutil

shutil.copy('/path/to/source/file', '/path/to/destination')

This will copy the file from the source location to the destination. If the destination is a directory, the file will be copied into that directory with the same name as the original file. If the destination is a file, it will be overwritten with the contents of the source file.

You can also use the shutil.copy2() function, which is similar to shutil.copy(), but also tries to preserve metadata like file permissions, modification times, and flags.

import shutil

shutil.copy2('/path/to/source/file', '/path/to/destination')

If you want to copy the contents of a directory, you can use the shutil.copytree() function. This function will recursively copy the directory and all its subdirectories and files.

import shutil

shutil.copytree('/path/to/source/directory', '/path/to/destination')
Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →