In Python, you can use the shutil
module to copy files using the shutil.copy()
function. Additionally, if you want to preserve the file metadata (such as timestamps and permissions), you can use shutil.copystat()
.
Here’s an example:
import shutil
def copy_file(src_path, dest_path):
try:
# Copy the file from src_path to dest_path
shutil.copy(src_path, dest_path)
# Copy the file metadata (timestamps, permissions, etc.)
shutil.copystat(src_path, dest_path)
print(f"File '{src_path}' copied to '{dest_path}' successfully.")
except FileNotFoundError:
print(f"Error: The file '{src_path}' does not exist.")
except PermissionError:
print(f"Error: Permission denied. Check if you have the necessary permissions.")
# Example usage:
source_file = 'path/to/source_file.txt'
destination_file = 'path/to/destination_file.txt'
copy_file(source_file, destination_file)
In this example:
- Replace
'path/to/source_file.txt'
with the actual path of the file you want to copy. - Replace
'path/to/destination_file.txt'
with the desired destination path for the copied file.
This script defines a function copy_file
that takes the source file path and the destination file path as parameters. It uses shutil.copy()
to copy the file and shutil.copystat()
to copy the file metadata.
Make sure that you have the necessary permissions to read from the source file and write to the destination file. If the destination file already exists, it will be overwritten.