How to copy files to a new directory using Python?


The act of copying files to a new directory is a basic skill that every developer in Python should invariably possess. Whether it is the process of backing up data, organizing files or creating a new project, there are powerful tools provided by Python to make file copying an easy task. In this extensive article, you will learn the process of copying files to a new directory using Python. Detailed explanations and practical code examples, will help you gain the knowledge and confidence to handle file copying tasks successfully.

Understanding File Copying

Before we begin with the examples in this article, let us take a moment to make sense of the concept of file copying. File copying means duplicating the contents of one file and storing it in or transferring it to a different location. This process enables us to take backups, move files around among directories, or even create several versions of the same file.

Copying a Single File

Let us consider a simple code example where we learn how to copy a single file to a new directory in Python.

Example

In this example, the shutil module is imported; it makes provisions for high-level file operations. We assign the path of the file we want to copy to the source_file variable. Next, we declare the destination_directory variable, which indicates the directory where we want to keep the copied file. Finally, the shutil.copy() function is made use of to perform the file copy operation.

import shutil

# Specify the source file path
source_file = '/path/to/your/source/file.txt'

# Specify the destination directory path
destination_directory = '/path/to/your/destination/directory/'

# Copy the file to the destination directory
shutil.copy(source_file, destination_directory)

Copying Multiple Files

Oftentimes, we may want to copy several files to a new directory at a go. The following code example shows you how to achieve this in Python.

Example

In this code example, we import the glob module together with the shutil module. We declare the source_directory variable to show the path to the directory containing the files we wish to copy or duplicate. Similarly, we declare the destination_directory variable as the target directory where we wish to keep the copied files. By using glob.glob() function with the pattern source_directory + '/*', we fetch a list of all files in the source directory. We then loop over each file and copy it to the destination directory making use of shutil.copy().

import shutil
import glob
# Specify the source directory path
source_directory = '/path/to/your/source/directory/'

# Specify the destination directory path
destination_directory = '/path/to/your/destination/directory/'
# Get a list of all files in the source directory

files = glob.glob(source_directory + '/*')

# Copy each file to the destination directory
for file in files:
   shutil.copy(file, destination_directory)

Copying Files with Renaming

In certain situations, we may want to copy files to a new directory after renaming the files. The code example given below shows how to accomplish this task in Python.

Example

In this code, we assign the source_file variable with the path of the file we wish to copy. We then declare the destination_file variable with the path and the new desired name of the copied file which is to be renamed.

By utilizing shutil.copy() function and giving the destination file path, we copy the file to the new directory while renaming it at the same accordingly.

import shutil

# Specify the source file path
source_file = '/path/to/your/source/file.txt'

# Specify the destination file path with the desired name
destination_file = '/path/to/your/destination/new_file.txt'

# Copy the file to the destination directory with renaming
shutil.copy(source_file, destination_file)

Output

For some particular source file, the output can be

/content/sample_data/newactive_config

Handling Errors and Exceptions

It's essential and important to handle possible errors and exceptions that may take place or happen during file copying operations. The following example shows you how to integrate error handling while you are copying the file.

Example

Here, in this snippet, we use a try-except block to tackle possible exceptions that may occur while the file copying process is underway. We make an attempt to copy the file making use of shutil.copy() within the try block. If a FileNotFoundError occurs, it implies that the source file does not exist. If an IsADirectoryError occurs, it indicates that the destination path points to a directory instead of a file. A PermissionError may occur if there are inadequate permissions to copy the file. At last, the except Exception block acts as a catch-all to handle any other unforeseen errors that may occur. By incorporating and integrating error handling, we can skillfully handle various scenarios during file copying.

import shutil

# Specify the source file path
source_file = '/path/to/your/source/file.txt'

# Specify the destination directory path
destination_directory = '/path/to/your/destination/directory/'

try:
   # Copy the file to the destination directory
   shutil.copy(source_file, destination_directory)
   print("File copied successfully!")
except FileNotFoundError:
   print("Source file not found.")
except IsADirectoryError:
   print("Destination is a directory.")
except PermissionError:
   print("Permission denied.")
except Exception as e:
   print("An error occurred:", str(e))

Output

For some particular source file, the output can be

File copied successfully!

In this comprehensive and extensive article, we navigated and explored the process of copying files to a new directory using Python. We considered code examples for copying a single file, copying several files, copying files along with renaming them and handling errors and exceptions that may arise. With these strategies at your disposal as your resource, you now can manage file-copying tasks with confidence in your Python projects. Keep in mind to consider the source file path, the destination directory, and any particular requirements such as renaming files. By doing file copying in Python like an expert, you can efficiently organize, backup, and manipulate files with ease, making you realize your coding prowess.

Updated on: 17-Jul-2023

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements