Python Series track

Week 04 · Intermediate Track

Week 4 — Standard Library

The Python standard library has batteries included. Learn the most useful modules: datetime for time, pathlib for files, collections for advanced data structures, and itertools for efficient looping.

Intermediate Track2 min readFree lesson

Level: Intermediate | Prerequisite: Week 3 (Module/Package)

Learning Goals

  • Handle date and time with datetime
  • Random values and sampling with random
  • File and folder paths with pathlib
  • Counter, defaultdict of collections

The standard library can be imported directly without additional installation.

1. datetime

from datetime import datetime, date, timedelta

now = datetime.now()
print(now)
print(now.strftime("%Y-%m-%d %H:%M"))

today = date.today()
birthday = date(2000, 5, 9)
days_lived = (today - birthday).days

next_week = now + timedelta(days=7)

2. random

import random

print(random.random())                  # 0.0 ~ 1.0
print(random.randint(1, 100))           #Integers 1 ~ 100
print(random.choice(["Scissors","Rock","Paper"]))
print(random.sample(range(1, 46), 6))   #Lotto
random.shuffle(my_list)                 #In-place shuffling

3. pathlib

Handle paths more cleanly than strings.

from pathlib import Path

p = Path("data") / "report.txt"        # data/report.txt
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text("hello", encoding="utf-8")
print(p.read_text(encoding="utf-8"))

print(p.exists(), p.suffix, p.name, p.stem)

#List of files in the folder
for f in Path(".").glob("*.py"):
    print(f.name, f.stat().st_size)

4. collections

from collections import Counter, defaultdict, deque

#Counter — Frequency count, one line
text = "to be or not to be"
print(Counter(text.split()))    # {'to': 2, 'be': 2, ...}
print(Counter(text.split()).most_common(2))

#defaultdict — Default value if key is missing
groups = defaultdict(list)
for name, age in [("A", 20), ("B", 25), ("C", 20)]:
    groups[age].append(name)
print(dict(groups))

#deque — Double-ended queue
dq = deque([1, 2, 3])
dq.appendleft(0)
dq.append(4)
print(dq)

Key Examples (examples/)

File Content
01_datetime.py Date/Time
02_random.py Random
03_pathlib.py Path
04_collections.py Counter, defaultdict

⚠️ Common Mistakes

  1. datetime vs date — datetime includes time, date only date.
  2. Don't know random.seed() — Set a seed like random.seed(42) to reproduce the same results.
  3. Adding path strings — Path("data") / "x" is safer than "data" + "/" + "x".

❓ FAQ

Q1. Difference between time and datetime? A. time is low-level (timestamp), datetime is high-level (object). Usually, datetime is enough.

Q2. Which to use, os.path or pathlib? A. For new code, pathlib is recommended. More OOP-like and readable.

📝 Exercises (exercises/)

  • exercise1.md — D-Day calculator
  • exercise2.md — Print sizes of .txt files in a folder
  • exercise3.md — Top 5 word frequencies (Counter)

Next Week

Week 5. Exception Handling

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

examples/01_datetime.pyPython
from datetime import datetime, date, timedelta

now = datetime.now()
print(now)
print(now.strftime("%Y-%m-%d %H:%M:%S"))
print(now.strftime("%Y year %m month %d day %A"))

today = date.today()
birthday = date(2000, 5, 9)
delta = today - birthday
print(f"{delta.days} days since birth")

next_week = now + timedelta(days=7)
print(f"Next week: {next_week.strftime('%Y-%m-%d')")

#Parse string to datetime
parsed = datetime.strptime("2026-05-09 14:30", "%Y-%m-%d %H:%M")
print(parsed)
examples/02_random.pyPython
import random

print(random.random())
print(random.randint(1, 100))
print(random.choice(["Scissors", "Rock", "Paper"]))
print(random.sample(range(1, 46), 6))

#Seed fixed → Reproducible
random.seed(42)
print([random.randint(1, 10) for _ in range(5)])

#Shuffle list (in place)
nums = [1, 2, 3, 4, 5]
random.shuffle(nums)
print(nums)

#Weighted selection
result = random.choices(["A", "B", "C"], weights=[5, 3, 1], k=10)
print(result)
examples/03_pathlib.pyPython
from pathlib import Path

#Path Combination
p = Path("data") / "report" / "summary.txt"
print(p)

#Create Parent Folder
p.parent.mkdir(parents=True, exist_ok=True)

#Write/Read
p.write_text("Hello
Python!", encoding="utf-8")
print(p.read_text(encoding="utf-8"))

#Information
print("Exists:", p.exists())
print("Name:", p.name)
print("Extension:", p.suffix)
print("Name (without extension):", p.stem)
print("Size:", p.stat().st_size)

#Traverse Folder
for f in Path(".").glob("*.py"):
    print(f.name)
examples/04_collections.pyPython
from collections import Counter, defaultdict, deque

# Counter
text = "the quick brown fox jumps over the lazy dog the quick"
words = text.split()
c = Counter(words)
print(c)
print(c.most_common(3))

#defaultdict — Automatically created if the key does not exist
groups = defaultdict(list)
for name, age in [("A", 20), ("B", 25), ("C", 20), ("D", 25)]:
    groups[age].append(name)
print(dict(groups))

#deque — Fast addition/removal from both ends
dq = deque([1, 2, 3])
dq.appendleft(0)
dq.append(4)
print(dq)
dq.popleft()
dq.pop()
print(dq)

Assignment

Goal

Takes the target date as input and outputs the remaining days.

Requirements

  • Format: YYYY-MM-DD
  • Calculate the difference with today
  • If past, D+N; if future, D-N

Input/Output Example

Target Date (YYYY-MM-DD): 2026-12-25
Today: 2026-05-09
D-230 until Christmas

Task 2. .txt File Sizes in Folder

Goal

Outputs all .txt files and their sizes (bytes) in a given folder.

Requirements

  • Use pathlib.Path.glob
  • Sort by size in descending order

Input/Output Example

Folder: ./data
report.txt           1,234 bytes
notes.txt              456 bytes
todo.txt                12 bytes
Total 3 files, 1,702 bytes

Task 3. Top 5 Word Frequencies (Counter)

Goal

Prints the top 5 most frequently appearing words in a long text.

Requirements

  • Use collections.Counter
  • Case-insensitive
  • Remove periods, commas, etc.

Hint

import re
words = re.findall(r"\w+", text.lower())
Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

solution1.pyPython
from datetime import date

target = input("Target Date (YYYY-MM-DD):").strip()
y, m, d = map(int, target.split("-"))
target_date = date(y, m, d)
today = date.today()

delta = (target_date - today).days
print(f"Today: {today}")
if delta > 0:
    print(f"D-{delta} until the target date")
elif delta < 0:
    print(f"D+{-delta} since the target date")
else:
    print("D-DAY!")
solution2.pyPython
from pathlib import Path

folder = Path(input("Folder path:").strip() or ".")
files = sorted(folder.glob("*.txt"), key=lambda p: -p.stat().st_size)

total = 0
for f in files:
    size = f.stat().st_size
    total += size
    print(f"{f.name:20} {size:>8,} bytes")
print(f"Total {len(files)} files, {total:,} bytes")
solution3.pyPython
from collections import Counter
import re

text = """
The quick brown fox jumps over the lazy dog. The dog is sleeping.
The fox runs quickly. Quickly! The fox ran over the dog.
The dog wakes up.
"""

words = re.findall(r"\w+", text.lower())
counter = Counter(words)

print("Top 5:")
for word, count in counter.most_common(5):
    print(f"{word}: {count} times")

Learn this lesson with a mentor

Work through the Python Series track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now