How to Copy Files in Python?

Estimated read time 2 min read

To copy files in Python, you can use the shutil module which provides a high-level interface for file operations. Here’s an example:

import shutil

# Replace 'source_file_path' with the path to the file you want to copy
source_file_path = 'path/to/source/file.txt'

# Replace 'destination_directory_path' with the path to the directory where you want to copy the file
destination_directory_path = 'path/to/destination/directory'

# Copy the file from the source path to the destination directory
shutil.copy(source_file_path, destination_directory_path)

In the above code, we first import the shutil module. We then specify the path to the file we want to copy (source_file_path) and the path to the directory where we want to copy the file (destination_directory_path).

We use the shutil.copy method to copy the file from the source path to the destination directory. This method preserves the original file’s metadata, including its creation and modification times, and copies the file’s contents to a new file in the destination directory.

If you want to preserve the original filename, you can specify the destination path as a file path instead of a directory path. For example:

import shutil

# Replace 'source_file_path' with the path to the file you want to copy
source_file_path = 'path/to/source/file.txt'

# Replace 'destination_file_path' with the path to the file where you want to copy the file
destination_file_path = 'path/to/destination/file.txt'

# Copy the file from the source path to the destination file path
shutil.copy(source_file_path, destination_file_path)

This will copy the file from the source path to the destination file path, preserving the original file’s metadata and contents, and using the same filename in the destination path.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply