os
One module, three jobs: talk to the environment (os.environ, getenv), manage files and folders (listdir, scandir, walk, makedirs, remove, replace, stat), and drive processes and file descriptors. Most of it is portable; a large part is Unix only, and every page here says which.
import os from os import path, environ import os.path
Demo
import os for f in ['README.md', 'src/app.py', 'src/util.py']: os.makedirs(os.path.dirname(f) or '.', exist_ok=True) open(f, 'w').close() try: result = sorted(os.listdir('.')) except OSError as e: result = type(e).__name__ result
listdir returns bare names — files and folders mixed, in no promised order — and raises FileNotFoundError for a missing folder and NotADirectoryError for a file (the message text differs between Linux and Windows; the class does not). In the environment tab, environment values must be str: os.environ['APP_MODE'] = 8080 raises TypeError: str expected, not int. getenv returns None, or your default, for a variable that is not set.
Members
Common patterns
import os PORT = int(os.environ.get('PORT', '8000')) DEBUG = os.getenv('DEBUG', '0') == '1'
import os os.makedirs('build/reports', exist_ok=True)
import os for root, dirs, files in os.walk('src'): for name in files: print(os.path.join(root, name))
import os with open('state.json.tmp', 'w', encoding='utf-8') as f: f.write(data) os.replace('state.json.tmp', 'state.json')
Examples
Pitfalls
import os from unittest import mock with mock.patch.dict(os.environ): os.environ['PORT'] = 8080
import os from unittest import mock with mock.patch.dict(os.environ): os.environ['PORT'] = str(8080) port = int(os.environ['PORT']) port
import os if not os.path.exists('out'): os.mkdir('out') os.path.isdir('out')
import os os.makedirs('out', exist_ok=True) os.makedirs('out', exist_ok=True) os.path.isdir('out')
When to use
- Environment variables, the current process, low-level OS calls
- Folder operations when you already work with str paths (listdir, walk, makedirs, remove, replace)
- Path arithmetic and reading/writing whole files → pathlib
- Copying, moving trees, deleting non-empty folders → shutil (copy2, copytree, move, rmtree)
- Running programs → subprocess instead of os.system / os.popen / spawn*
- Temporary files and folders → tempfile
Notes
FAQ
os is the operating-system interface (environment, processes, creating and deleting files and folders). os.path is a separate module of path-string helpers — join, split, splitext, exists — imported automatically as an attribute of os. It is posixpath on Linux and macOS and ntpath on Windows.