Module 15 · Python Standard Libraries — topic 5 of 13
os
Talking to the operating system with os: environment variables, the working directory, listing and scanning folders, creating and removing files and directories, walking trees, and portable path helpers.
Learning objectives
- Read and set environment variables
- Inspect and change directories
- Scan folders efficiently with os.scandir and os.walk
Definition
The os module provides a portable interface to operating-system features: environment variables, process information, the current directory, and file and directory operations. os.path contains path utilities.
Introduction
Scripts often need to know where they are running, read configuration from the environment, or manage folders. os is the toolbox for that.
Why it matters
Environment variables are the standard way to configure applications and keep secrets out of code; os makes them easy to use.
Detailed explanation
os.environ is a dictionary-like mapping of environment variables; os.getenv("NAME", default) reads one safely. Setting os.environ["NAME"] affects this process and its children.
os.getcwd() returns the current working directory; os.chdir(path) changes it (affecting relative paths).
os.listdir(path) lists names; os.scandir(path) yields DirEntry objects with is_file(), is_dir() and stat() — faster when you need details.
os.makedirs creates nested folders, os.remove deletes files, os.rmdir deletes empty folders, os.rename and os.replace rename.
os.walk(top) visits every folder in a tree, yielding (folder, subfolders, files).
os.name is "nt" on Windows and "posix" elsewhere; os.sep is the path separator; os.cpu_count() reports processor cores.
For paths, pathlib is often clearer, but os and os.path remain common in existing code.
Syntax
- getenv for configuration.
- scandir for detailed listings.
- walk for whole trees.
Code examples
Environment variables
testing default testing
Folders and the working directory
['a.txt', 'b.csv', 'raw'] True True
More examples
Scanning a folder tree
file a.txt 5 file b.txt 2 dir img - total bytes: 13 True
Step-by-step explanation
- scandir returns entries that already know whether they are files or folders, avoiding extra system calls.
- os.walk visits docs and docs/img, and the generator expression sums every file's size.
- os.name lets code branch on the operating system when it must.
Expected output
Running “Scanning a folder tree” prints exactly:
Practical applications
- Reading DATABASE_URL or API keys from the environment.
- Disk-usage reports and cleanup scripts.
Best practices
- Configure apps with environment variables.
- Use scandir for listings with details.
- Prefer pathlib for path manipulation in new code.
Common mistakes
Hard-coding secrets
Avoid
Prefer
Secrets in code leak through version control; the environment keeps them separate.
Relying on listdir order
Avoid
Prefer
The order is arbitrary and differs between systems.
Important notes
- os.system and os.popen run shell commands, but subprocess is the safer, more flexible choice.
Key takeaways
- os.environ and getenv read configuration.
- listdir, scandir and walk explore folders.
- os provides portable OS operations.
Try it yourself
- 1Print every environment variable whose name starts with PY.
- 2Find the largest file under a folder using os.walk.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
1 question test this exact topic. Answers and explanations are revealed after you submit.
- ModerateWhat is printed?