How to Copy Files in Python?

Better Stack Team
Updated on November 23, 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')

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github