Mathew K Analytics

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.…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

Python 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)
3.12.1 (tags/v3.12.1:2305ca5, Dec  7 2023, 22:03:25) [MSC v.1937 64 bit (AMD64)]
win32
nt

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)
['C:\\Users\\makmw\\AppData\\Roaming\\Python\\Python312\\site-packages\\ipykernel_launcher.py', '--f=c:\\Users\\makmw\\AppData\\Roaming\\jupyter\\runtime\\kernel-v36ba72af36d6f10ab7aaba59acb087e45b615cf00.json']
<class 'list'>
2
C:\Users\makmw\AppData\Roaming\Python\Python312\site-packages\ipykernel_launcher.py

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])
<class 'list'>
10
c:\Users\makmw\AppData\Local\Programs\Python\Python312\python312.zip
c:\Users\makmw\AppData\Local\Programs\Python\Python312\DLLs
c:\Users\makmw\AppData\Local\Programs\Python\Python312\Lib
/some/custom/directory

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)
written directly to stdout
UTF-8
written directly to stderr
hello

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'))
<class 'os._Environ'>
hello
hello
None
default value
hello

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())
c:\PythonTraining\Full_videos\Notebooks
c:\PythonTraining\Full_videos\Notebooks\demo_subdir
c:\PythonTraining\Full_videos\Notebooks

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())
['file_a.txt', 'file_b.txt', 'inner']
file_a.txt False True
file_b.txt False True
inner True False

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))
demo_listing\file_a.txt
True
True
True
file_a.txt
demo_listing
('demo_listing\\file_a', '.txt')
c:\PythonTraining\Full_videos\Notebooks\demo_listing\file_a.txt

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'))
True
True
True
False
False
import shutil
shutil.rmtree('demo_nested')
shutil.rmtree('demo_listing')
shutil.rmtree('demo_subdir')
print(os.path.isdir('demo_nested'))
False

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}')
13344
16
makmw

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}')
Validation passed
Would exit with code: 0
Would exit with code: 1
Error: negative value

Part 12: sys.getsizeof() and Interpreter Internals#

print(sys.getsizeof(42))
print(sys.getsizeof('hello'))
print(sys.getsizeof([1, 2, 3]))
print(sys.getrecursionlimit())
28
46
88
3000

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'))
production
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)
data/reports/summary.csv
data\reports\summary.csv
False

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.