🔄 Quick Recap (Day 17)

  • You created concise lists with list comprehensions.

  • You built generators for memory-efficient data processing.

🎯 What You’ll Learn Today

  1. How to use os for filesystem tasks (directories, paths).

  2. How to leverage sys to access interpreter information.

  3. Working with dates and times via datetime and timedelta.

  4. Serializing data with json and counting with collections.Counter.

📖 Filesystem with os

The os module interacts with your computer’s file system:

  • Get current directory:

    import os
    cwd = os.getcwd()
    print(f"Current directory: {cwd}")
  • List directory contents:

    entries = os.listdir(cwd)
    print("Entries:", entries)
  • Create directories safely:

    os.makedirs('data_dir/subdir', exist_ok=True)
  • Check file/folder existence:

    exists = os.path.exists('data_dir')
    print(f"data_dir exists? {exists}")

Use os.sep for cross-platform path separators and os.path.join() to construct paths reliably.

📖 Interpreter Info with sys

The sys module provides access to runtime information:

  • Command-line arguments (including script name):

    import sys
    print("Arguments:", sys.argv)
  • Python version and build info:

    print("Python version:", sys.version)
  • Exit codes: Use sys.exit(code) to terminate your script with a status.

This helps in writing scripts that respond to user input or environment settings.

📖 Dates & Times with datetime

Working with dates/times is easy using datetime:

  • Current date and time:

    from datetime import datetime
    now = datetime.now()
    print("Now:", now)
  • Formatting output:

    formatted = now.strftime('%Y-%m-%d %H:%M:%S')
    print("Formatted:", formatted)
  • Date arithmetic:

    from datetime import timedelta
    tomorrow = now + timedelta(days=1)
    yesterday = now - timedelta(days=1)
    print("Tomorrow:", tomorrow.date())
    print("Yesterday:", yesterday.date())

Use these to timestamp logs or compute durations.

📖 JSON Serialization & Counter

JSON with json

Convert Python objects ↔ JSON strings:

import json

person = {"name": "Alice", "age": 30}
json_text = json.dumps(person)
print("JSON text:", json_text)

loaded = json.loads(json_text)
print("Loaded dict:", loaded)

Use indent= in dumps() for human-readable files and json.dump() to write directly to files.

Counting with collections.Counter

Quickly tally items in a list:

from collections import Counter
fruits = ["apple", "banana", "apple", "cherry", "banana"]
cnt = Counter(fruits)
print("Counts:", cnt)
print("Most common:", cnt.most_common(1))

Counter is ideal for word counts, tallying votes, or tracking occurrences.

🧙‍♂️ Take the Wand and Try Yourself

  1. Create stdlib_practice.py.

  2. Filesystem: Make a folder data_dir, then inside create a file data_dir/info.json.

    • Use os.makedirs and open() or json.dump().

  3. Write Data: In info.json, save a dictionary with keys "name" (your name) and "date" (today’s date from datetime).

  4. Read Data: Load info.json back into a dict and print it.

  5. Count Words: Given a list words = ['alpha','beta','alpha','gamma'], use Counter to print the most common word.

Solution Example (stdlib_practice.py):

import os, json
from datetime import datetime
from collections import Counter

# Create folder path
dir_path = 'data_dir'
os.makedirs(dir_path, exist_ok=True)

# Prepare data
data = {'name': 'Alice', 'date': datetime.now().strftime('%Y-%m-%d')}

# Write JSON file
file_path = os.path.join(dir_path, 'info.json')
with open(file_path, 'w') as f:
    json.dump(data, f, indent=2)

# Read JSON file
with open(file_path, 'r') as f:
    loaded = json.load(f)
print(loaded)

# Count words
def count_words(words_list):
    counts = Counter(words_list)
    return counts.most_common(1)

words = ['alpha','beta','alpha','gamma']
print(count_words(words))

Expected output:

{'name': 'Alice', 'date': '2025-07-20'}
[('alpha', 2)]

Run:

python stdlib_practice.py

Once you see the correct JSON data and the most common word, you’ve harnessed key parts of Python’s standard library!

Up next: Day 19: Consuming APIs


Keep Reading