How to Copy Files to Another Directory in Python?

In this tutorial, I will explain how to copy files to another directory in Python. During a project for one of my clients, I had the requirement to organize files and back up data. Copying files offers various ways to accomplish this efficiently. Let’s get into the various methods and best practices for copying files in Python.

Copy Files to Another Directory in Python

Let us learn how to copy files to another directory in Python.

Read How to Open a File in Python?

Use the shutil Module

The shutil module is the most common and versatile way to copy files in Python. It offers several functions for copying files and directories.

1. Copy a Single File

To copy a single file, you can use the shutil.copy() function in Python. This function copies the content and metadata of the source file to the destination file.

import shutil

# Define the source and destination paths
source_path = '/Users/johndoe/Documents/report.txt'
destination_path = '/Users/johndoe/Backup/report.txt'

# Copy the file
shutil.copy(source_path, destination_path)
print("File copied successfully.")

I executed the above example code and added the screenshot below.

Copy Files to Another Directory in Python

In this example, the file report.txt is copied from the Documents directory to the Backup directory.

Check out How to Unzip a File in Python?

2. Copy a File with Metadata

If you also need to copy the file’s metadata, such as the last modification time, you can use shutil.copy2() in Python.

import shutil

# Define the source and destination paths
source_path = '/Users/janedoe/Documents/data.csv'
destination_path = '/Users/janedoe/Backup/data.csv'

# Copy the file with metadata
shutil.copy2(source_path, destination_path)
print("File copied with metadata successfully.")

I executed the above example code and added the screenshot below.

How to Copy Files to Another Directory in Python

Read How to Read Tab-Delimited Files in Python?

3. Copy Multiple Files

To copy multiple files from one directory to another, you can use a loop in combination with Python shutil.copy() method.

import shutil
import os

# Define the source and destination directories
source_dir = '/Users/michaelsmith/Documents/Projects'
destination_dir = '/Users/michaelsmith/Backup/Projects'

# Copy each file in the source directory to the destination directory
for filename in os.listdir(source_dir):
    source_file = os.path.join(source_dir, filename)
    destination_file = os.path.join(destination_dir, filename)
    if os.path.isfile(source_file):
        shutil.copy(source_file, destination_file)
        print(f'Copied {filename} to {destination_dir}')

This script copies all files from the Projects directory in Documents to the Projects directory in Backup.

Read How to Split a File into Multiple Files in Python?

Use the os Module

The os module in Python can also be used to copy files, though it requires a bit more code. This method is useful if you need more control over the copying process.

Copy a File

Here’s how to copy a file using the os module:

import os

# Define the source and destination paths
source_path = '/Users/annawilliams/Documents/notes.txt'
destination_path = '/Users/annawilliams/Backup/notes.txt'

# Open the source file and read its contents
with open(source_path, 'rb') as file_src:
    content = file_src.read()

# Write the contents to the destination file
with open(destination_path, 'wb') as file_dest:
    file_dest.write(content)

print("File copied using os module.")

I executed the above example code and added the screenshot below.

Copy Files to Another Directory in Python os module

Check out How to Skip the First Line in a File in Python?

Handle Errors

When copying files, it’s important to handle potential errors, such as file not found or permission denied. Using try-except blocks can help manage these situations gracefully.

import shutil

source_path = '/Users/johndoe/Documents/missingfile.txt'
destination_path = '/Users/johndoe/Backup/missingfile.txt'

try:
    shutil.copy(source_path, destination_path)
    print("File copied successfully.")
except FileNotFoundError:
    print(f"The file {source_path} does not exist.")
except PermissionError:
    print(f"Permission denied while copying {source_path}.")

Read How to Read XML Files in Python?

Conclusion

In this tutorial, I explained how to copy files to another directory in Python. I discussed copying files to another directory using shutil module to copy a single file, copy a file with metadata , and copy multiple files. and using the os module to copy a file. I also discussed how to handle errors.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.