๐ฅ๏ธ OS Module
The os module provides a portable way of using operating system dependent functionality.
Mastering this concept will significantly boost your Python data science skills!
๐ป Code Example:
import os import shutil from pathlib import Path # 1. Environment variables print("HOME :", os.environ.get("HOME", "N/A")) print("USER :", os.environ.get("USERNAME", os.environ.get("USER", "N/A"))) print("PATH entries:", len(os.environ.get("PATH", "").split(os.pathsep))) # 2. Current working directory cwd = os.getcwd() print("\nCWD:", cwd) # 3. List and filter directory contents entries = os.listdir(".") py_files = [f for f in entries if f.endswith(".py")] dirs = [f for f in entries if os.path.isdir(f)] print(f"Python files: {len(py_files)} | Dirs: {len(dirs)}") # 4. Walk directory tree โ find all .md files md_files = [] for root, dirs_found, files in os.walk("pynfinity/static/pebbles_content"): for filename in files: if filename.endswith(".md"): md_files.append(os.path.join(root, filename)) print(f"\nTotal .md pebbles: {len(md_files)}") # 5. Create, rename, remove test_dir = Path("pynfinity_test_dir/subdir") test_dir.mkdir(parents=True, exist_ok=True) test_file = test_dir / "hello_pynfinity.txt" test_file.write_text("Hello from pynfinity!\n", encoding="utf-8") # Rename file renamed = test_dir / "pynfinity_hello.txt" os.rename(test_file, renamed) print(f"\nFile content: {renamed.read_text().strip()}") # 6. Disk space check stat = shutil.disk_usage("/") print(f"\nDisk: Total={stat.total//2**30}GB | " f"Used={stat.used//2**30}GB | Free={stat.free//2**30}GB") # Cleanup shutil.rmtree("pynfinity_test_dir") print("Cleanup complete.")
Keep exploring and happy coding! ๐ป