🐍 Python for Everyone

← Back to the quiz

Chapter 13 Exercises 30 min, hands-on

Exercises: File Handling & CSV

How to run these Download all the files below into the same folder (starter.py, tasks.txt, and inventory.csv), then run python3 starter.py from inside that folder — the sample data files use plain relative filenames, so the script must be run from the same folder they're in.

1 Opening & reading files

Write a function count_lines(filename) that opens the file with with, reads all its lines with .readlines(), and returns how many there are. Call it with "tasks.txt" and print the result.

2 Writing to files

Write a function save_tasks(filename, tasks) that opens filename in write mode ("w") and writes each string in the tasks list on its own line. Call it with "new_tasks.txt" and ["Buy stamps", "Renew license"], then open the file again and print its contents.

3 Appending to files

Write a function add_task(filename, task) that opens filename in append mode ("a") and writes task on a new line. Call it on "new_tasks.txt" with "Schedule dentist", then open the file again and print its contents — the two tasks from Task 2 should still be there.

4 Reading CSV with csv.DictReader

Write a function total_inventory_value(filename) that opens filename with csv.DictReader and returns the sum of quantity * price across every row (convert row["quantity"] to int and row["price"] to float). Call it with "inventory.csv" and print the result.

5 Writing CSV with csv.DictWriter

Write a function export_low_stock(input_filename, output_filename, threshold) that reads input_filename with csv.DictReader, collects every row where int(row["quantity"]) < threshold, and writes those rows to output_filename using csv.DictWriter with fieldnames=["item", "quantity", "price"] (remember newline="" and .writeheader()). Call it with "inventory.csv", "low_stock.csv", and 20, then open "low_stock.csv" and print its contents.

6 Handling FileNotFoundError

Write a function read_safely(filename) that tries to open and read filename, returning its contents. If a FileNotFoundError happens, print f"'{filename}' was not found." and return None. Call it with "does_not_exist.txt" and print the result.

🐞 Task 7 — Debug the Code

This code logs each visit to a file, but it opens the file in "w" mode instead of "a" mode — every call wipes out every visit logged before it, so only the most recent visit ever survives. Find and fix the mode so every visit is kept.

buggy_wrong_mode.py
def log_visit(filename, username):
    with open(filename, "w") as file:
        file.write(username + " visited\n")

log_visit("visits.txt", "alice")
log_visit("visits.txt", "bob")

with open("visits.txt") as file:
    print(file.read())

🐞 Task 8 — Debug the Code

This code opens a file the manual way, with no with statement and no .close() call at all — a file handle leak waiting to happen. Find and fix it so the file is opened with with instead, guaranteeing it gets closed automatically.

buggy_no_with.py
def read_report(filename):
    file = open(filename)
    contents = file.read()
    return contents

print(read_report("inventory.csv"))
← Back to Quiz Practice Bank →