The Python os module provides a portable way of using operating system-dependent functionality. It enables you to interface with the underlying operating system, allowing you to perform tasks such as reading environment variables, navigating directories, and managing files and directories programmatically.
Core Operating System Operations
This section covers fundamental operations for interacting with the file system and operating environment. Before using these functions, import the module with import os.
Checking System Information
The os.name attribute reveals the type of operating system currently running. A return value of posix indicates a Unix-like system (Linux, macOS), while nt represents Windows systems.
import os
print(os.name) # Output: 'nt' on Windows, 'posix' on Unix-like systems
Managing Environment Variables
Environment variables store configuration information that can be accessed by processes. The os.environ object behaves like a dictionary, allowing you to view and retrieve environment variables.
import os
# Retrieve all environment variables
print(os.environ)
# Access a specific environment variable
print(os.environ.get("PATH"))
print(os.environ.get("USERNAME"))
Working with Directories
Directory operations form the backbone of file system manipulation. Understanding how to navigate, create, and modify directories is essential for file management tasks.
import os
# Get current working directory
print(os.getcwd())
# List contents of a directory
print(os.listdir()) # Current directory contents
print(os.listdir("/path/to/directory")) # Specific directory contents
# Reference special directory entries
print(os.curdir) # Current directory (.)
print(os.pardir) # Parent directory (..)
# Create a new directory
try:
os.mkdir(os.path.join(os.getcwd(), "output"))
except FileExistsError:
print("Directory already exists")
# Remove an empty directory
os.rmdir(os.path.join(os.getcwd(), "output"))
# Get file metadata
file_info = os.stat("document.txt")
print(f"File size: {file_info.st_size} bytes")
# Rename a file or directory
os.rename("old_name.txt", "new_name.txt")
# Delete a file
os.remove("unnecessary.txt")
Path Manipulation with os.path
The os.path subomdule provides functions for manipulating file paths in a cross-platform manner. These functions handle the differences between Windows (backslashes) and Unix-based systems (forward slashes) automatically.
Checking Path Properties
Before performing operations on paths, you often need to verify whether a path exists and what type of entity it represents.
import os
# Check if path exists
print(os.path.exists("/path/to/file.txt"))
# Determine if path is a file or directory
print(os.path.isdir("/path/to/directory"))
print(os.path.isfile("/path/to/file.txt"))
# Check if path is absolute
print(os.path.isabs("/absolute/path"))
print(os.path.isabs("relative/path"))
# Get file size (0 for directories)
print(os.path.getsize("/path/to/file.txt"))
Path Decomposition and Composition
Breaking down paths into components and reconstructing them enables flexible path manipulation without hardcoding separators.
import os
# Split a path into directory and filename
print(os.path.split("/home/user/documents/report.txt"))
# Output: ('/home/user/documents', 'report.txt')
# Separate filename from extension
print(os.path.splitext("document.pdf"))
# Output: ('document', '.pdf')
# Combine path components
full_path = os.path.join("/home/user", "documents", "file.txt")
print(full_path)
# Output: /home/user/documents/file.txt
# Get absolute path from relative path
print(os.path.abspath("data/input.csv"))
# Extract directory name
print(os.path.dirname("/home/user/project/app.py"))
# Extract base filename
print(os.path.basename("/home/user/project/app.py"))
Practical Path Operations
The following example demonstrates combining multiple path operations to accomplish a common task: verifying a file's existence and accessibility before processing.
import os
def verify_file_access(file_path):
"""Check if a file exists and is readable."""
if not os.path.exists(file_path):
return False, "File does not exist"
if not os.path.isfile(file_path):
return False, "Path is not a file"
if not os.access(file_path, os.R_OK):
return False, "File is not readable"
return True, f"File ready ({os.path.getsize(file_path)} bytes)"
# Usage example
success, message = verify_file_access("data/config.json")
print(message)
These path manipulation functions abstract away platform-specific details, making your code portable across different operating systems without modification. Always use os.path functions instead of string concatenation with path separators to ensure your applications work correctly on all platforms.
When working with file paths, remember that os.path.join() handles separator differences automatically, and os.path.normpath() can resolve redundant separators and relative path references to produce a canonical path representation.