
PYTHON — Copy Move Rename in Python
Simplicity is the soul of efficiency. — Austin Freeman

# Tutorial: Copy, Move, and Rename Files in Python
In Python, copying, moving, and renaming files and directories can be achieved using various built-in functions and modules. The shutil (shell utilities) module and the os module provide the necessary functionality for these file operations.
Copying Files and Directories
To copy a file in Python, you can use the shutil.copy() function. This function takes in a source file path and a destination file path and creates a copy of the file at the specified destination. The shutil.copy2() function can also be used to copy the metadata of the file along with its contents.
import shutil
# Copy a file
shutil.copy('source_file.txt', 'destination_file.txt')To copy a directory and its contents, you can use the shutil.copytree() function. This function copies the entire directory tree to the specified destination.
# Copy a directory
shutil.copytree('source_directory', 'destination_directory')Moving and Renaming Files and Directories
To move or rename a file in Python, you can use the shutil.move() function. This function takes in a source path and a destination path. If the source and destination are on the same filesystem, shutil.move() performs an efficient file rename. However, it can also handle moving files across different filesystems by performing a copy and delete operation.
# Move a file
shutil.move('source_file.txt', 'destination_folder/source_file.txt')Similarly, the os.rename() function can be used to rename or move files and directories within the same filesystem.
import os
# Rename a file
os.rename('old_name.txt', 'new_name.txt')Conclusion
In this tutorial, you learned how to copy, move, and rename files and directories in Python using the shutil module and the os module. These file operations are essential for managing and organizing files within a Python program. By using these functions and modules, you can efficiently handle file manipulation tasks in your Python scripts.
Now you can utilize the code snippets provided to perform file operations in your Python projects.

