This tutorial provides a comprehensive guide to essential file and directory manipulation in Python, leveraging the power of the os
and shutil
modules. We’ll cover creating, accessing, listing, modifying, and removing directories, equipping you with the skills to manage your file system effectively within your Python scripts.
Table of Contents
- Creating Directories
- Getting the Current Directory
- Listing Directory Contents
- Changing the Working Directory
- Renaming and Removing Directories
- Path Manipulation Techniques
- Robust Error Handling
1. Creating Directories
The os
module offers functions for interacting with the operating system. os.mkdir()
creates a single directory, while os.makedirs()
handles the creation of nested directories. The exist_ok
parameter prevents errors if the directory already exists.
import os
# Create a single directory
os.mkdir("my_new_directory")
# Create nested directories
os.makedirs("nested/directories/example", exist_ok=True)
print("Directories created successfully!")
2. Getting the Current Directory
Use os.getcwd()
to retrieve the current working directory.
import os
current_directory = os.getcwd()
print(f"Current working directory: {current_directory}")
3. Listing Directory Contents
os.listdir()
lists all entries (files and directories) within a path. Combine it with os.path.isdir()
to filter for directories only.
import os
directory_path = "."
all_entries = os.listdir(directory_path)
directories = [entry for entry in all_entries if os.path.isdir(os.path.join(directory_path, entry))]
print("Directories:")
for directory in directories:
print(directory)
4. Changing the Working Directory
os.chdir()
alters the current working directory. Always include error handling (e.g., using try-except
blocks) to manage potential issues like non-existent directories.
import os
try:
os.chdir("my_new_directory")
print(f"Current working directory changed to: {os.getcwd()}")
os.chdir("..") #Go back up one directory level
print(f"Current working directory changed back to: {os.getcwd()}")
except FileNotFoundError:
print("Error: Directory not found.")
except OSError as e:
print(f"An OS error occurred: {e}")
5. Renaming and Removing Directories
os.rename()
renames directories. os.rmdir()
removes empty directories. For non-empty directories, use shutil.rmtree()
with extreme caution, as it recursively deletes everything within the target directory. Always back up important data before using this function.
import os
import shutil
# Rename a directory
os.rename("my_new_directory", "renamed_directory")
# Remove an empty directory
os.rmdir("empty_directory") #Requires an empty directory named "empty_directory"
# Remove a non-empty directory (use with extreme caution!)
shutil.rmtree("non_empty_directory") #Requires a directory named "non_empty_directory" - this will delete everything within.
print("Directory operations completed.")
6. Path Manipulation Techniques
The os.path
module provides tools for safe and portable path manipulation, crucial for avoiding platform-specific issues.
import os
# Joining paths safely
path = os.path.join("path", "to", "my", "file.txt")
# Getting file name and extension
file_name, file_ext = os.path.splitext(path)
# Checking if a path exists
if os.path.exists(path):
print("Path exists")
7. Robust Error Handling
Always anticipate potential errors (e.g., FileNotFoundError
, PermissionError
, OSError
) and implement appropriate error handling mechanisms to make your code robust and prevent unexpected crashes.