To copy and rename a file in Python, you can use the
copy method to make a copy of the file, and then use the
rename method to rename the copied file. Here’s an example:
import shutil import os # Replace 'source_file_path' with the path to the file you want to copy and rename 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/' # Replace 'new_file_name' with the new name you want to give the copied file new_file_name = 'new_file_name.txt' # Make a copy of the file in the destination directory shutil.copy(source_file_path, destination_directory_path) # Build the path to the copied file in the destination directory copied_file_path = os.path.join(destination_directory_path, os.path.basename(source_file_path)) # Rename the copied file to the new name os.rename(copied_file_path, os.path.join(destination_directory_path, new_file_name))
In the above code, we first import the
os modules. We then specify the path to the file we want to copy and rename (
source_file_path), the path to the directory where we want to copy the file (
destination_directory_path), and the new name we want to give the copied file (
We use the
shutil.copy method to make a copy of the file in the destination directory. We then use the
os.path.join method to build the path to the copied file in the destination directory and store it in the
Finally, we use the
os.rename method to rename the copied file to the new name. We pass the
copied_file_path as the old path and the new file name along with the destination directory path as the new path.
Note that if the destination directory already contains a file with the same name as the new name you want to give the copied file, the
os.rename method will overwrite the existing file. If you want to avoid overwriting files, you can check if the file already exists before copying and renaming it, and choose a different name if necessary.