The shutil
module provides a high-level interface for file and directory operations. It offers functions to copy, move, and delete files and directories, as well as other utility functions for working with file paths.
Here are a few practical examples of how you can use the shutil
module:
1. Copying Files:
The shutil
module provides the shutil.copy()
function to copy files from one location to another.
import shutil # Copy a file to a new location shutil.copy("source_file.txt", "destination_folder/")
In this code, we use the shutil.copy()
function to copy the file "source_file.txt"
to the "destination_folder/"
.
2. Moving Files:
The shutil
module provides the shutil.move()
function to move files or directories to a new location.
import shutil # Move a file to a new location shutil.move("source_file.txt", "destination_folder/")
In this code, we use the shutil.move()
function to move the file "source_file.txt"
to the "destination_folder/"
.
3. Deleting Files:
The shutil
module provides the shutil.rmtree()
function to delete directories and their contents recursively.
import shutil # Delete a directory and its contents shutil.rmtree("directory_to_delete/")
In this code, we use the shutil.rmtree()
function to delete the directory "directory_to_delete/"
and all its contents.
The shutil
module offers many more functions for file and directory operations, such as archiving, file permissions, and symbolic links. It provides a convenient and high-level interface for common file and directory tasks.