To copy a file to another directory with a new name in Python, you can use the shutil
library. Here's how you can do it:
import shutil
# Specify the source file path
source_file = 'path/to/source/file.txt'
# Specify the destination directory
destination_directory = 'path/to/destination/'
# Specify the new name for the copied file
new_file_name = 'new_file.txt'
# Create the full destination path
destination_path = destination_directory + new_file_name
# Copy the file to the destination directory with the new name
shutil.copy2(source_file, destination_path)
In this code, replace 'path/to/source/file.txt'
with the path to the source file you want to copy, 'path/to/destination/'
with the path to the destination directory, and 'new_file.txt'
with the new name you want to assign to the copied file.
The shutil.copy2
function is used to copy the file to the destination with its new name. It preserves file metadata during the copy. If you don't need to preserve metadata, you can use shutil.copy
instead:
shutil.copy(source_file, destination_path)
This code will copy the file from the source path to the destination directory with the specified new name. If the destination directory doesn't exist, it will be created.
- directory another Python Copy filedirectory another python copy file importerror directory python directory python file such shared file directory libraries directory fatal error file libcudnn_cnn_infer file directory libcudnn shared file ogg_linux_x directory interpreter directory file such file directory nginx after directory macos node file