os, sys & pathlib
os, sys & pathlib
Section titled “os, sys & pathlib”Simple Analogy 📂
Section titled “Simple Analogy 📂”os= Your computer’s file manager — create folders, delete files, get environment variablessys= The Python interpreter’s control panel — command-line args, exit codes, Python versionpathlib= A modern GPS for file paths — cleaner, more intuitive thanos.path
pathlib — Modern Path Handling
Section titled “pathlib — Modern Path Handling”Python 3.4+ introduced pathlib — the modern way to handle file paths. It’s cleaner than os.path.
from pathlib import Path
# Create a pathp = Path("documents/report.txt")print(p) # documents\report.txt (Windows) # documents/report.txt (Mac/Linux)
# Path componentsprint(p.name) # report.txtprint(p.stem) # report (no extension)print(p.suffix) # .txtprint(p.parent) # documentsprint(p.parents[0]) # documentsprint(p.parents[1]) # . (current dir)
# Building pathsconfig = Path("config") / "app" / "settings.json"print(config) # config/app/settings.json
# Home directoryhome = Path.home()print(home) # C:\Users\Me or /home/me
# Current directorycwd = Path.cwd()print(cwd)File Operations with pathlib
Section titled “File Operations with pathlib”from pathlib import Path
# Check if existsp = Path("data.txt")print(p.exists()) # True/Falseprint(p.is_file()) # True/Falseprint(p.is_dir()) # True/False
# Read and writep.write_text("Hello, World!") # Write filecontent = p.read_text() # Read entire fileprint(content) # Hello, World!
# Binary modep.write_bytes(b"\x00\x01\x02")data = p.read_bytes()
# List directory contentsfor f in Path(".").iterdir(): print(f.name)
# Glob (pattern match)for py in Path(".").glob("**/*.py"): print(py)
# Create directoriesPath("new_folder/subfolder").mkdir(parents=True, exist_ok=True)
# Renamep.rename("new_name.txt")
# Deleteif p.exists(): p.unlink() # Delete fileos — Operating System Interface
Section titled “os — Operating System Interface”import os
# Environment variablesprint(os.environ.get("HOME")) # /home/userprint(os.environ.get("PATH")) # /usr/bin:/bin:...print(os.getenv("HOME")) # Same, but simpler
# Set environment variableos.environ["MY_VAR"] = "hello"
# Current working directorycwd = os.getcwd()os.chdir("/tmp") # Change directory
# Files and directoriesos.makedirs("a/b/c", exist_ok=True)os.remove("file.txt")os.rmdir("empty_folder")
# List directoryprint(os.listdir("."))
# System infoprint(os.name) # 'posix' or 'nt' (Windows)print(os.cpu_count()) # Number of CPUssys — System-Specific Parameters
Section titled “sys — System-Specific Parameters”import sys
# Command-line arguments# Run: python script.py --verbose file.txtprint(sys.argv)# ['script.py', '--verbose', 'file.txt']
# Exit the programsys.exit(0) # Successsys.exit(1) # Error
# Python versionprint(sys.version) # '3.12.0 (main, Oct 2 2024, ...)'print(sys.version_info) # sys.version_info(major=3, minor=12, micro=0)
# Module search pathprint(sys.path)# ['', '/usr/lib/python312.zip', '/usr/lib/python3.12', ...]
# Platformprint(sys.platform) # 'win32', 'linux', 'darwin' (Mac)Quick Comparison: os.path vs pathlib
Section titled “Quick Comparison: os.path vs pathlib”| Task | os.path (old) | pathlib (modern) |
|---|---|---|
| Join paths | os.path.join("a", "b") | Path("a") / "b" |
| Get filename | os.path.basename(path) | Path(path).name |
| Get extension | os.path.splitext(path)[1] | Path(path).suffix |
| Check existence | os.path.exists(path) | Path(path).exists() |
| List directory | os.listdir(".") | Path(".").iterdir() |
| Read file | open("f.txt").read() | Path("f.txt").read_text() |
🧠 In Simple Words
Section titled “🧠 In Simple Words”pathlib.Pathis the modern way to handle file paths — more intuitive thanos.pathosgives you environment variables, process info, and OS operationssysgives you command-line args, Python version, and the module search path- Prefer
pathlibfor file paths, useosonly for environment variables and system info - Use
sys.argvto read command-line arguments when running scripts