88. Python's os and shutil Modules
The os and shutil modules in Python are widely used for managing files and directories, as well as performing various file operations. Below are 10 Python code snippets demonstrating the capabilities of these modules.
1. Creating Directories with os.makedirs
import os
# Create a directory along with intermediate directories
directory_path = 'parent_folder/child_folder'
os.makedirs(directory_path, exist_ok=True)
print(f"Directory created: {directory_path}")os.makedirs creates directories, and the exist_ok=True argument ensures it doesn't raise an error if the directory already exists.
2. Renaming a File with os.rename
import os
# Rename a file
old_name = 'old_file.txt'
new_name = 'new_file.txt'
os.rename(old_name, new_name)
print(f"File renamed from {old_name} to {new_name}")os.rename renames or moves a file. It works for both renaming and moving files across directories.
3. Removing a File with os.remove
os.remove deletes a file. You can use this method to delete files from the filesystem.
4. Listing Files in a Directory with os.listdir
os.listdir returns a list of files and directories in the specified path.
5. Copying a File with shutil.copy
shutil.copy copies the contents of a file to another location, preserving the file permissions.
6. Moving a File with shutil.move
shutil.move moves a file or directory to a new location, and it can also be used to rename files.
7. Removing an Empty Directory with os.rmdir
os.rmdir removes an empty directory. If the directory contains files, it will raise an error.
8. Deleting a Directory and Its Contents with shutil.rmtree
shutil.rmtree removes a directory along with all its contents, including files and subdirectories.
9. Getting File Information with os.stat
os.stat provides detailed information about a file, such as size, creation time, and last modification time.
10. Changing File Permissions with os.chmod
os.chmod changes the permissions of a file. In this case, it grants read and write permissions to the owner only.
These 10 snippets highlight the key functionalities of the os and shutil modules for handling file and directory operations in Python. These modules provide a wide range of useful tools for managing filesystem operations in a scriptable and automated manner.
Last updated