Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 08 / Stage 1

Files, text and data formats

Goal: Read and write text, JSON and CSV files safely, work with paths and timestamps, and pull data out of text with regular expressions. Time: ~1 hour

What you will learn

  • Opening files with with open(...)
  • File modes: r, w, a, x (and binary b)
  • Reading: read(), readline(), looping over lines
  • Writing text to files
  • Encodings and why to always pass encoding="utf-8"
  • pathlib: Path, the / operator, exists, read_text, write_text, glob, mkdir, parent, name, suffix
  • JSON: dumps, loads, dump, load, indent
  • CSV: reader, writer, DictReader, DictWriter, newline=""
  • Dates and times in files: timestamps, ISO format, strptime
  • Regular expressions: search, findall, sub (also with a function), fullmatch, groups, named groups, raw strings

The snippets below create small demo_* files in your current folder. Run them in an empty practice folder, or delete the files afterwards (section 6 shows how with unlink()).

Topics in this part

Practice

Python workbench — write and run code here

Press Run and Python 3.14 loads right in your browser (a one-time download of about 15 MB; after that it works offline). Your code never leaves this page. input() opens a small prompt window.

Rules for every exercise:

  • Use with open(..., encoding="utf-8") or Path.read_text / write_text.
  • Open CSV files with newline="" as well.
  • Put your demo code under if __name__ == "__main__":.
  • Build paths with Path(__file__).parent so the program works from any folder.
  • Delete any demo files your program creates at the end.

Exercise 1: Quick notes app

Scenario: You want a tiny app that remembers your to-do notes in a text file.

What to do:

  • Write add_note(text) that appends one line to demo_notes.txt.
  • Write show_notes() that prints each note with a number, or No notes yet. if the file is missing.
  • Demo: show (empty), add 3 notes (one with ₹, one in Hindi), show again.

Sample output:

No notes yet.
1. Call plumber at 5 pm
2. Pay school fees ₹12,500
3. Buy दही (curd)

💡 Hint: mode "a", enumerate(f, start=1) and line.rstrip().


Show the solution to Exercise 1
"""Exercise 1: Quick notes app (append and read a text file).

Run: python ex01.py   (macOS/Linux: python3 ex01.py)
"""

from pathlib import Path

NOTES = Path(__file__).parent / "demo_notes.txt"


def add_note(text: str) -> None:
    with open(NOTES, "a", encoding="utf-8") as f:   # "a" keeps old notes
        f.write(text + "\n")


def show_notes() -> None:
    if not NOTES.exists():
        print("No notes yet.")
        return
    with open(NOTES, encoding="utf-8") as f:
        for number, line in enumerate(f, start=1):
            print(f"{number}. {line.rstrip()}")


if __name__ == "__main__":
    NOTES.unlink(missing_ok=True)   # start fresh for the demo
    show_notes()
    add_note("Call plumber at 5 pm")
    add_note("Pay school fees ₹12,500")
    add_note("Buy दही (curd)")
    show_notes()
    NOTES.unlink()                  # clean up

Exercise 2: Word counter

Scenario: A teacher wants quick stats for a student's essay file.

What to do:

  • Write the essay below into demo_essay.txt.
  • Write count_file(path) that returns lines, words, characters (without newlines) and the top 3 words (lowercase, no punctuation).

Starting data:

SAMPLE = """India is a big country.
India has many languages and many festivals.
People in India love cricket and food.
"""

Sample output:

Lines: 3
Words: 19
Characters (no newlines): 105
Top 3 words: [('india', 3), ('many', 2), ('and', 2)]

💡 Hint: loop over the file line by line; line.split() gives words. Clean each word with word.strip(".,!?").lower() so "country." and "Country" both count as "country". Count words in a dict with counts[w] = counts.get(w, 0) + 1, then sorted(counts.items(), key=lambda pair: pair[1], reverse=True)[:3] (words with the same count keep the order they were first seen, so many comes before and).


Show the solution to Exercise 2
"""Exercise 2: Word counter for a text file.

Run: python ex02.py   (macOS/Linux: python3 ex02.py)
"""

from pathlib import Path

ESSAY = Path(__file__).parent / "demo_essay.txt"

SAMPLE = """India is a big country.
India has many languages and many festivals.
People in India love cricket and food.
"""


def count_file(path: Path) -> dict:
    lines = words = chars = 0
    word_counts: dict[str, int] = {}
    with open(path, encoding="utf-8") as f:
        for line in f:
            lines += 1
            chars += len(line.rstrip("\n"))
            line_words = line.split()
            words += len(line_words)
            for word in line_words:
                word = word.strip(".,!?").lower()
                word_counts[word] = word_counts.get(word, 0) + 1
    # Sort (word, count) pairs by count, biggest first; ties keep first-seen order
    ranked = sorted(word_counts.items(), key=lambda pair: pair[1], reverse=True)
    return {"lines": lines, "words": words, "chars": chars, "top": ranked[:3]}


if __name__ == "__main__":
    ESSAY.write_text(SAMPLE, encoding="utf-8")
    stats = count_file(ESSAY)
    print(f"Lines: {stats['lines']}")
    print(f"Words: {stats['words']}")
    print(f"Characters (no newlines): {stats['chars']}")
    print("Top 3 words:", stats["top"])
    ESSAY.unlink()

Exercise 3: Downloads folder organiser

Scenario: Your Downloads folder is a mess. Sort files into folders by type.

What to do:

  • Create a demo_downloads folder with these empty files (use touch()): trip.jpg, aadhaar.pdf, song.mp3, resume.docx, logo.PNG, notes.xyz.
  • Go through the files in name order (sorted(folder.iterdir())) and move .jpg/.png → Images, .pdf/.docx → Documents, .mp3 → Music, anything else → Others. The case of the suffix does not matter (.PNG is an image).
  • If a file with the same name is already in the target folder, skip it and print a message instead of moving it.
  • Print how many files went to each folder, list every file (sorted) as Folder/name, then delete everything.

Sample output:

Moved: {'Documents': 2, 'Images': 2, 'Others': 1, 'Music': 1}
   Documents/aadhaar.pdf
   Documents/resume.docx
   Images/logo.PNG
   Images/trip.jpg
   Music/song.mp3
   Others/notes.xyz
Cleaned up: True

💡 Hint: file.suffix.lower(), folder.mkdir(exist_ok=True), file.rename(new_path). sorted(folder.iterdir()) makes a list (a snapshot) before the loop starts, which matters because you add folders and move files while looping. Check new_path.exists() before rename(): on Windows rename() fails if the target exists, on macOS / Linux it silently overwrites it. To delete, remove files first, then the empty folders (rmdir()), deepest first.


Show the solution to Exercise 3
"""Exercise 3: Downloads folder organiser (pathlib).

Run: python ex03.py   (macOS/Linux: python3 ex03.py)
"""

from pathlib import Path

DOWNLOADS = Path(__file__).parent / "demo_downloads"

FOLDER_FOR = {
    ".jpg": "Images", ".png": "Images",
    ".pdf": "Documents", ".docx": "Documents",
    ".mp3": "Music",
}


def organise(folder: Path) -> dict[str, int]:
    moved: dict[str, int] = {}
    # Take a snapshot of the folder first: sorted() reads every entry into a list
    # before the loop starts. We create sub-folders and move files while looping,
    # so looping over a live iterdir() could miss or repeat entries. sorted() also
    # keeps the order the same on every computer.
    for file in sorted(folder.iterdir()):
        if not file.is_file():
            continue
        target_name = FOLDER_FOR.get(file.suffix.lower(), "Others")
        target = folder / target_name
        target.mkdir(exist_ok=True)
        new_path = target / file.name
        # rename() on Windows fails if new_path exists; on macOS/Linux it would
        # silently overwrite that file. Check first, so both behave the same.
        if new_path.exists():
            print(f"Skipped {file.name}: {target_name}/{file.name} already exists")
            continue
        file.rename(new_path)
        moved[target_name] = moved.get(target_name, 0) + 1
    return moved


def remove_tree(folder: Path) -> None:
    """Delete files first, then folders (deepest first)."""
    deepest_first = sorted(folder.rglob("*"), key=lambda p: len(p.parts), reverse=True)
    for path in deepest_first:
        if path.is_file():
            path.unlink()
        else:
            path.rmdir()
    folder.rmdir()


if __name__ == "__main__":
    DOWNLOADS.mkdir(exist_ok=True)
    names = [
        "trip.jpg", "aadhaar.pdf", "song.mp3",
        "resume.docx", "logo.PNG", "notes.xyz",
    ]
    for name in names:
        (DOWNLOADS / name).touch()   # make an empty file

    print("Moved:", organise(DOWNLOADS))
    for path in sorted(DOWNLOADS.rglob("*.*")):
        # as_posix() always uses "/", even on Windows
        print("  ", path.relative_to(DOWNLOADS).as_posix())
    remove_tree(DOWNLOADS)
    print("Cleaned up:", not DOWNLOADS.exists())

Exercise 4: Phone book in JSON

Scenario: Save contacts so they are still there when you open the app tomorrow.

What to do:

  • Store contacts as a dict: {"Asha Verma": {"phone": "...", "city": "..."}}.
  • Write load(), save(contacts), add(...) and search(contacts, text) (case-insensitive, part of the name).
  • Add the 3 contacts below, save, load them again (like opening the app the next day), search for "ash", print Ravi's city, then print the first 5 lines of the file.

Starting data:

add(contacts, "Asha Verma", "98765 43210", "Lucknow")
add(contacts, "Ravi Kumar", "91234 56789", "Chennai")
add(contacts, "Ashok Rao", "99887 66554", "Mysuru")

Sample output:

Saved 3 contacts
Search 'ash': ['Asha Verma', 'Ashok Rao']
Ravi's city: Chennai

First lines of the file:
{
  "Asha Verma": {
    "phone": "98765 43210",
    "city": "Lucknow"
  },

💡 Hint: json.dumps(data, indent=2, ensure_ascii=False) and json.loads(text). Return {} if the file does not exist yet. Keep phone numbers as strings.


Show the solution to Exercise 4
"""Exercise 4: Phone book saved to JSON.

Run: python ex04.py   (macOS/Linux: python3 ex04.py)
"""

import json
from pathlib import Path

BOOK = Path(__file__).parent / "demo_contacts.json"


def load() -> dict[str, dict]:
    if not BOOK.exists():
        return {}
    return json.loads(BOOK.read_text(encoding="utf-8"))


def save(contacts: dict[str, dict]) -> None:
    text = json.dumps(contacts, indent=2, ensure_ascii=False)
    BOOK.write_text(text, encoding="utf-8")


def add(contacts: dict[str, dict], name: str, phone: str, city: str) -> None:
    contacts[name] = {"phone": phone, "city": city}


def search(contacts: dict[str, dict], text: str) -> list[str]:
    text = text.lower()
    return [name for name in contacts if text in name.lower()]


if __name__ == "__main__":
    contacts = load()
    add(contacts, "Asha Verma", "98765 43210", "Lucknow")
    add(contacts, "Ravi Kumar", "91234 56789", "Chennai")
    add(contacts, "Ashok Rao", "99887 66554", "Mysuru")
    save(contacts)
    print(f"Saved {len(contacts)} contacts")

    again = load()  # like opening the app the next day
    print("Search 'ash':", search(again, "ash"))
    print("Ravi's city:", again["Ravi Kumar"]["city"])
    print("\nFirst lines of the file:")
    for line in BOOK.read_text(encoding="utf-8").splitlines()[:5]:
        print(line)
    BOOK.unlink()

Exercise 5: Monthly expenses summary (CSV)

Scenario: You export your expenses as CSV and want a total per category.

What to do:

  • Write demo_expenses.csv with the rows below (first row = header date,category,amount).
  • Read it with csv.DictReader and add up amount per category.
  • Write demo_summary.csv with category,total,share using csv.DictWriter, biggest first. Print the summary file, then the grand total.

Starting data:

ROWS = [
    ["date", "category", "amount"],
    ["2025-03-01", "Food", "250"],
    ["2025-03-02", "Travel", "120"],
    ["2025-03-05", "Food", "480"],
    ["2025-03-07", "Bills", "1240"],
    ["2025-03-09", "Travel", "60"],
    ["2025-03-12", "Food", "320"],
]

Sample output:

category,total,share
Bills,1240.0,50%
Food,1050.0,43%
Travel,180.0,7%
Grand total: ₹2,470.00

💡 Hint: open CSV files with newline="". csv.writer(f).writerows(ROWS) writes all rows at once. Convert row["amount"] with float(). Format a share with f"{x:.0%}" and the grand total with f"₹{grand:,.2f}".


Show the solution to Exercise 5
"""Exercise 5: Monthly expenses CSV summary.

Run: python ex05.py   (macOS/Linux: python3 ex05.py)
"""

import csv
from pathlib import Path

HERE = Path(__file__).parent
EXPENSES = HERE / "demo_expenses.csv"
SUMMARY = HERE / "demo_summary.csv"

ROWS = [
    ["date", "category", "amount"],
    ["2025-03-01", "Food", "250"],
    ["2025-03-02", "Travel", "120"],
    ["2025-03-05", "Food", "480"],
    ["2025-03-07", "Bills", "1240"],
    ["2025-03-09", "Travel", "60"],
    ["2025-03-12", "Food", "320"],
]


def summarise(path: Path) -> dict[str, float]:
    totals: dict[str, float] = {}
    with open(path, newline="", encoding="utf-8") as f:
        for row in csv.DictReader(f):
            category = row["category"]
            totals[category] = totals.get(category, 0) + float(row["amount"])
    return totals


if __name__ == "__main__":
    with open(EXPENSES, "w", newline="", encoding="utf-8") as f:
        csv.writer(f).writerows(ROWS)

    totals = summarise(EXPENSES)
    grand = sum(totals.values())

    with open(SUMMARY, "w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=["category", "total", "share"])
        writer.writeheader()
        biggest_first = sorted(totals.items(), key=lambda pair: pair[1], reverse=True)
        for category, amount in biggest_first:
            share = f"{amount / grand:.0%}"
            writer.writerow({"category": category, "total": amount, "share": share})

    print(SUMMARY.read_text(encoding="utf-8"), end="")
    print(f"Grand total: ₹{grand:,.2f}")
    EXPENSES.unlink()
    SUMMARY.unlink()

Exercise 6: Birthday reminder

Scenario: A family app reminds you of birthdays coming up in the next 30 days.

What to do:

  • Save the list below as demo_birthdays.json (dates as ISO text).
  • Load it, turn each date into a date with date.fromisoformat().
  • List people whose birthday is within 30 days of a fixed today = date(2025, 2, 25), nearest first, with the age they will turn.
  • Someone born on 29 February (Dev) has no birthday in a non-leap year. In those years, use 1 March.

Starting data:

DATA = [
    {"name": "Asha", "born": "1998-03-14"},
    {"name": "Ravi", "born": "2001-03-20"},
    {"name": "Meena", "born": "1995-12-25"},
    {"name": "Kiran", "born": "2000-02-25"},
    {"name": "Dev", "born": "2004-02-29"},
]

Sample output:

Birthdays in the next 30 days (from 25 Feb 2025):
  Kiran turns 25 TODAY 🎂
  Dev turns 21 in 4 day(s)
  Asha turns 27 in 17 day(s)
  Ravi turns 24 in 23 day(s)

💡 Hint: born.replace(year=today.year) gives this year's birthday. It raises ValueError for 29 Feb in a non-leap year: catch it and use date(year, 3, 1) instead. If the birthday is already past, use next year. The age they turn is birthday.year - born.year. Put (days_left, name, age) tuples in a list and sorted() it: tuples sort by their first item.


Show the solution to Exercise 6
"""Exercise 6: Birthday reminder from a JSON file with ISO dates.

Run: python ex06.py   (macOS/Linux: python3 ex06.py)
"""

import json
from datetime import date
from pathlib import Path

BIRTHDAYS_FILE = Path(__file__).parent / "demo_birthdays.json"

DATA = [
    {"name": "Asha", "born": "1998-03-14"},
    {"name": "Ravi", "born": "2001-03-20"},
    {"name": "Meena", "born": "1995-12-25"},
    {"name": "Kiran", "born": "2000-02-25"},
    {"name": "Dev", "born": "2004-02-29"},   # leap-day birthday
]


def birthday_in(born: date, year: int) -> date:
    """The birthday in a given year. 29 Feb falls back to 1 March in non-leap years."""
    try:
        return born.replace(year=year)
    except ValueError:              # 29 Feb does not exist in this year
        return date(year, 3, 1)


def next_birthday(born: date, today: date) -> date:
    this_year = birthday_in(born, today.year)
    if this_year < today:           # already passed -> next year
        return birthday_in(born, today.year + 1)
    return this_year


def upcoming(path: Path, today: date, within: int = 30) -> list[tuple[int, str, int]]:
    """Return (days_left, name, age_turning) tuples, nearest birthday first."""
    people = json.loads(path.read_text(encoding="utf-8"))
    result = []
    for person in people:
        born = date.fromisoformat(person["born"])
        birthday = next_birthday(born, today)
        days_left = (birthday - today).days
        if days_left <= within:
            turning = birthday.year - born.year
            result.append((days_left, person["name"], turning))
    return sorted(result)   # tuples sort by their first item: days_left


if __name__ == "__main__":
    BIRTHDAYS_FILE.write_text(json.dumps(DATA, indent=2), encoding="utf-8")
    today = date(2025, 2, 25)
    print(f"Birthdays in the next 30 days (from {today:%d %b %Y}):")
    for days_left, name, turning in upcoming(BIRTHDAYS_FILE, today):
        when = "TODAY 🎂" if days_left == 0 else f"in {days_left} day(s)"
        print(f"  {name} turns {turning} {when}")
    BIRTHDAYS_FILE.unlink()

Exercise 7: Server log report

Scenario: Your team lead wants a short JSON report from yesterday's server log.

What to do:

  • Save the log lines below as server.log, next to your script, then read it with Path(__file__).parent / "server.log". (If you're working inside the course repo, you can instead read the full examples/sample_server.log.)
  • Use a regex with named groups to split each line into when, level, service, message.
  • Collect: first and last time (ISO), number of errors per service, unique users who logged in, the slowest GET request and the average response time of the GET requests only (rounded to a whole number of ms).
  • Save it as demo_log_report.json with indent=2, print it, then delete it.

Starting data (save as server.log):

2025-03-10 09:15:02 INFO [web] User asha logged in from 192.168.1.10
2025-03-10 09:15:45 INFO [web] GET /products 200 120ms
2025-03-10 09:16:10 WARNING [db] Slow query took 2300ms
2025-03-10 09:17:33 ERROR [payment] Payment failed for order #4521: card declined
2025-03-10 09:18:01 INFO [web] User ravi logged in from 10.0.0.25
2025-03-10 09:18:20 INFO [web] GET /cart 200 85ms
2025-03-10 09:19:55 ERROR [web] GET /checkout 500 1500ms
2025-03-10 09:20:12 INFO [web] User meena logged in from 192.168.1.10
2025-03-10 09:21:40 WARNING [auth] 3 failed logins for user kiran
2025-03-10 09:22:05 ERROR [payment] Payment failed for order #4530: timeout
2025-03-10 09:23:30 INFO [web] GET /products 200 95ms
2025-03-10 09:24:18 INFO [web] User ravi logged out

Sample output:

{
  "first": "2025-03-10T09:15:02",
  "last": "2025-03-10T09:24:18",
  "errors_by_service": {
    "payment": 2,
    "web": 1
  },
  "unique_users": [
    "asha",
    "meena",
    "ravi"
  ],
  "slowest_request": {
    "path": "/checkout",
    "status": 500,
    "ms": 1500
  },
  "average_ms": 450
}

💡 Hint: r"(?P<when>\S+ \S+) (?P<level>[A-Z]+) \[(?P<service>\w+)\] (?P<message>.*)". A set is not JSON, so convert it with sorted(users).


Show the solution to Exercise 7
"""
Exercise 7: Server log report.

Reads ../examples/sample_server.log and writes a JSON summary
next to this script (deleted at the end).

Run: python ex07.py   (macOS/Linux: python3 ex07.py)
"""

import json
import re
from datetime import datetime
from pathlib import Path

HERE = Path(__file__).parent
LOG = HERE.parent / "examples" / "sample_server.log"
REPORT = HERE / "demo_log_report.json"

LINE = re.compile(
    r"(?P<when>\S+ \S+) (?P<level>[A-Z]+) \[(?P<service>\w+)\] (?P<message>.*)"
)
REQUEST = re.compile(r"GET (?P<path>\S+) (?P<status>\d{3}) (?P<ms>\d+)ms")


def build_report(log_path: Path) -> dict:
    errors_by_service: dict[str, int] = {}
    users: set[str] = set()
    requests = []
    times = []

    with open(log_path, encoding="utf-8") as f:
        for line in f:
            m = LINE.search(line)
            if not m:
                continue
            times.append(datetime.strptime(m["when"], "%Y-%m-%d %H:%M:%S"))
            if m["level"] == "ERROR":
                service = m["service"]
                errors_by_service[service] = errors_by_service.get(service, 0) + 1
            login = re.search(r"User (\w+) logged in", m["message"])
            if login:
                users.add(login.group(1))
            request = REQUEST.search(m["message"])
            if request:
                requests.append({
                    "path": request["path"],
                    "status": int(request["status"]),
                    "ms": int(request["ms"]),
                })

    slowest = max(requests, key=lambda req: req["ms"])
    all_ms = [req["ms"] for req in requests]
    return {
        "first": times[0].isoformat(timespec="seconds"),
        "last": times[-1].isoformat(timespec="seconds"),
        "errors_by_service": errors_by_service,
        "unique_users": sorted(users),
        "slowest_request": slowest,
        "average_ms": round(sum(all_ms) / len(all_ms)),
    }


if __name__ == "__main__":
    report = build_report(LOG)
    REPORT.write_text(json.dumps(report, indent=2), encoding="utf-8")
    print(REPORT.read_text(encoding="utf-8"))
    REPORT.unlink()

Exercise 8: Find and mask contact details

Scenario: Before sharing a support chat, hide customers' emails and mobile numbers.

What to do:

  • Use the chat text below. Find all emails and Indian mobile numbers (10 digits starting with 6–9, optional +91 in front).
  • Mask emails as a*********@example.com (keep first letter and domain).
  • Mask mobiles as XXXXXX3210 (keep last 4 digits; the +91 goes too). Landlines like 080-2345678 must not change.

Starting data:

message = (
    "Contact Asha at [email protected] or +91 9876543210. "
    "Ravi: [email protected], 9123456789. Office: 080-2345678 (landline)."
)

Sample output:

Emails : ['[email protected]', '[email protected]']
Mobiles: ['9876543210', '9123456789']

Masked:
Contact Asha at a*********@example.com or XXXXXX3210. Ravi: r*****@mail.co.in, XXXXXX6789. Office: 080-2345678 (landline).

💡 Hint: re.sub can take a function instead of a replacement string: it gets the match object and returns the new text (README section 10). Use named groups like (?P<user>...). Write digits as [0-9], and use \b (word boundary) so a 10-digit match cannot start or end in the middle of a longer number. With two groups findall returns tuples, so for emails use [m.group(0) for m in EMAIL.finditer(text)].

Show the solution to Exercise 8
"""Exercise 8: Find and mask emails and mobile numbers (regex).

Run: python ex08.py   (macOS/Linux: python3 ex08.py)
"""

import re

EMAIL = re.compile(r"\b(?P<user>[\w.+-]+)@(?P<domain>[\w-]+\.[\w.]+)\b")
# Indian mobile: optional +91, then 10 digits starting with 6-9.
# (?:...) is a group that does NOT capture, so findall returns only <number>.
# [0-9] instead of \d: \d would also accept digits from other scripts.
MOBILE = re.compile(r"(?:\+91[\s-]?)?\b(?P<number>[6-9][0-9]{9})\b")


def find_contacts(text: str) -> dict[str, list[str]]:
    return {
        # finditer gives one match object per email; group(0) is the whole email
        # (findall would give (user, domain) tuples, because there are 2 groups)
        "emails": [m.group(0) for m in EMAIL.finditer(text)],
        "mobiles": MOBILE.findall(text),   # one group -> list of just the group
    }


def mask_email(m: re.Match) -> str:
    """re.sub calls this for every email match and uses the returned text."""
    user = m["user"]
    return f"{user[0]}{'*' * (len(user) - 1)}@{m['domain']}"


def mask(text: str) -> str:
    text = EMAIL.sub(mask_email, text)
    text = MOBILE.sub(lambda m: "XXXXXX" + m["number"][-4:], text)
    return text


if __name__ == "__main__":
    message = (
        "Contact Asha at [email protected] or +91 9876543210. "
        "Ravi: [email protected], 9123456789. Office: 080-2345678 (landline)."
    )
    found = find_contacts(message)
    print("Emails :", found["emails"])
    print("Mobiles:", found["mobiles"])
    print("\nMasked:")
    print(mask(message))

Common mistakes

Mistake Why it is wrong Fix
f = open(...) without with Easy to forget f.close(); data may not be saved Always with open(...) as f:
Opening with "w" when you meant to add "w" empties the file first Use "a" to append
No encoding="utf-8" Hindi, ₹, emoji break on some systems Always pass encoding="utf-8"
f.write(25) write only takes strings f.write(f"{25}\n") or str(25)
Forgetting "\n" with write All text ends up on one line Add "\n" or use print(..., file=f)
Relative path like open("data.csv") Depends on where you run Python from Path(__file__).parent / "data.csv"
CSV without newline="" Blank rows between lines on Windows open(path, "w", newline="", encoding="utf-8")
Using CSV values as numbers Every CSV value is a string int(row["maths"])
json.dump with a datetime or set TypeError: not JSON serializable Save dt.isoformat(), list(my_set)
Regex without r"..." "\b" becomes a backspace character Use raw strings r"\b\d+\b"
Using m.group() when search found nothing m is None, so AttributeError if m: before using it

Quick recap

  • Use with open(path, mode, encoding="utf-8"). It closes the file for you.
  • r read, w overwrite, a append, x create-new-only, add b for binary.
  • Loop over f to read big files line by line.
  • pathlib.Path joins paths with / and has read_text, write_text, glob, mkdir.
  • JSON: dump/load for files, dumps/loads for strings.
  • CSV: open with newline=""; DictReader/DictWriter use column names.
  • Store timestamps as ISO text; read back with fromisoformat or strptime.
  • Regex: search finds one, findall finds all, sub replaces; use raw strings and groups.

Checklist

  • I can read a file whole, line by line, and with readline().
  • I know the difference between w, a and x modes.
  • I always pass encoding="utf-8" and know why.
  • I can build paths with pathlib and find files with glob.
  • I can save a list of dicts to JSON and load it back.
  • I can read a CSV with DictReader and write one with DictWriter.
  • I can save a timestamp to a file and parse it back into a datetime.
  • I can use re.search, re.findall and groups to pull data from a log line.

Search the guide