Lesson 1 · Python standard library deep dive
Python os & sys Explained: Files, Env Vars & Args | Standard Library #1
Video one of the twenty-five-part series: os and sys, the two modules that connect a Python program to the operating system and the interpreter running it.…
- CoursePython standard library deep dive
- Lesson1 of 24
- Video20 min
- FormatJupyter notebook · 15 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbPython Standard Library Deep-Dive, Video 1: os and sys#
- Video one of the twenty-five-part series: os and sys, the two modules that connect a Python program to the operating system and the interpreter running it.
- Environment variables, directories, processes, command-line arguments, and standard streams.
- Let's get into it.
Part 1: What os and sys Are For#
import os
import sys
print(sys.version)
print(sys.platform)
print(os.name)
Part 2: sys.argv - Command-Line Arguments#
print(sys.argv)
print(type(sys.argv))
print(len(sys.argv))
script_name = sys.argv[0]
print(script_name)
Part 3: sys.path - the Module Search Path#
print(type(sys.path))
print(len(sys.path))
for entry in sys.path[:3]:
print(entry)
sys.path.append('/some/custom/directory')
print(sys.path[-1])
Part 4: Standard Streams: stdin, stdout, stderr#
sys.stdout.write('written directly to stdout\n')
sys.stderr.write('written directly to stderr\n')
print('hello', file=sys.stderr)
print(sys.stdout.encoding)
Part 5: os.environ - Environment Variables#
print(type(os.environ))
os.environ['MY_CUSTOM_VAR'] = 'hello'
print(os.environ['MY_CUSTOM_VAR'])
print(os.environ.get('MY_CUSTOM_VAR'))
print(os.environ.get('DOES_NOT_EXIST'))
print(os.environ.get('DOES_NOT_EXIST', 'default value'))
print(os.getenv('MY_CUSTOM_VAR'))
Part 6: The Current Working Directory#
print(os.getcwd())
starting_dir = os.getcwd()
os.makedirs('demo_subdir', exist_ok=True)
os.chdir('demo_subdir')
print(os.getcwd())
os.chdir(starting_dir)
print(os.getcwd())
Part 7: Listing Directory Contents#
os.makedirs('demo_listing/inner', exist_ok=True)
with open('demo_listing/file_a.txt', 'w') as f:
f.write('a')
with open('demo_listing/file_b.txt', 'w') as f:
f.write('b')
names = os.listdir('demo_listing')
print(sorted(names))
for entry in os.scandir('demo_listing'):
print(entry.name, entry.is_dir(), entry.is_file())
Part 8: os.path Basics#
full_path = os.path.join('demo_listing', 'file_a.txt')
print(full_path)
print(os.path.exists(full_path))
print(os.path.isfile(full_path))
print(os.path.isdir('demo_listing'))
print(os.path.basename(full_path))
print(os.path.dirname(full_path))
print(os.path.splitext(full_path))
print(os.path.abspath(full_path))
Part 9: Creating and Removing Files and Directories#
os.mkdir('demo_single')
print(os.path.isdir('demo_single'))
os.makedirs('demo_nested/a/b/c', exist_ok=True)
print(os.path.isdir('demo_nested/a/b/c'))
os.rename('demo_single', 'demo_renamed')
print(os.path.isdir('demo_renamed'))
os.rmdir('demo_renamed')
print(os.path.isdir('demo_renamed'))
os.remove('demo_listing/file_a.txt')
print(os.path.exists('demo_listing/file_a.txt'))
import shutil
shutil.rmtree('demo_nested')
shutil.rmtree('demo_listing')
shutil.rmtree('demo_subdir')
print(os.path.isdir('demo_nested'))
Part 10: Process Information#
print(os.getpid())
print(os.cpu_count())
try:
print(os.getlogin())
except OSError as e:
print(f'getlogin unavailable here: {e}')
Part 11: sys.exit() and Exit Codes#
def validate(value):
if value < 0:
print('Error: negative value', file=sys.stderr)
return 1
print('Validation passed')
return 0
exit_code = validate(5)
print(f'Would exit with code: {exit_code}')
exit_code = validate(-1)
print(f'Would exit with code: {exit_code}')
Part 12: sys.getsizeof() and Interpreter Internals#
print(sys.getsizeof(42))
print(sys.getsizeof('hello'))
print(sys.getsizeof([1, 2, 3]))
print(sys.getrecursionlimit())
Part 13: Common Patterns#
def get_config(key, default=None):
value = os.environ.get(key, default)
if value is None:
raise ValueError(f'Required config {key} is missing')
return value
os.environ['APP_MODE'] = 'production'
print(get_config('APP_MODE'))
print(get_config('LOG_LEVEL', 'INFO'))
bad_path = 'data' + '/' + 'reports' + '/' + 'summary.csv'
good_path = os.path.join('data', 'reports', 'summary.csv')
print(bad_path)
print(good_path)
print(bad_path == good_path)
Wrap-Up: What You Learned#
- sys connects to the interpreter: argv, path, standard streams, exit, getsizeof, recursion limit.
- os connects to the operating system: environ, working directory, listing, os.path basics.
- Creating and removing files and directories, and process information like PID and CPU count.
- Two genuinely practical patterns: environment-based configuration and cross-platform path joining.
- That wraps up os and sys. Next up: pathlib, the modern, object-oriented replacement for os.path.
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



