🔄 Quick Recap (Day 17)
You created concise lists with list comprehensions.
You built generators for memory-efficient data processing.
🎯 What You’ll Learn Today
How to use
osfor filesystem tasks (directories, paths).How to leverage
systo access interpreter information.Working with dates and times via
datetimeandtimedelta.Serializing data with
jsonand counting withcollections.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
Create
stdlib_practice.py.Filesystem: Make a folder
data_dir, then inside create a filedata_dir/info.json.Use
os.makedirsandopen()orjson.dump().
Write Data: In
info.json, save a dictionary with keys"name"(your name) and"date"(today’s date fromdatetime).Read Data: Load
info.jsonback into a dict and print it.Count Words: Given a list
words = ['alpha','beta','alpha','gamma'], useCounterto 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.pyOnce 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