🐍 Python for Everyone

← Back to exercises

Chapter 13 Practice Bank 70-90 min, hands-on

Practice Bank: File Handling & CSV

A deeper set of practice problems, organized by topic, for extra reps beyond the main exercises — including scenario-based problems written in the same style you'll meet in real interviews. Uses everything from Chapters 1-12 plus this chapter's own toolkit: open()/file I/O with with, .read()/.readline()/.readlines(), write ("w") and append ("a") modes, "r+", relative vs. absolute paths, the csv module (csv.reader/csv.writer/ csv.DictReader/csv.DictWriter), and FileNotFoundError/PermissionError handling. No other class besides a custom exception subclassing Exception, and no import beyond math/datetime/random/csv.

A note on the sample files Every sample data file these problems read from (notes.txt, settings.txt, sales.csv, sales_extra.csv, app.log, orders.csv) lives in this same practice/ folder. Download them alongside starter.py and run everything from inside this folder — a plain relative filename like "notes.txt" only resolves correctly when Python is run from the same folder the file lives in.
How to run these Download starter.py and the sample data files below into one folder, then run python3 starter.py from inside that same folder.

Topic 1: Opening & Reading Files

1 Reading a whole file

Find # TODO 1.1. Write read_whole_file(filename), opening with with and returning file.read().

2 Counting lines

Find # TODO 1.2. Write count_lines(filename), returning how many lines .readlines() found.

3 Reading just the first line

Find # TODO 1.3. Write first_line(filename), returning just file.readline().strip().

4 Looping over a file's lines

Find # TODO 1.4. Write lines_as_list(filename), looping over the file object directly and returning a stripped list.

5 Debug the Code

Find # TODO 1.5. This function opens a file the manual way with no with statement and no .close() call — a file handle leak. Fix it.

💼 Scenario

Loading a config file at startup

Find # TODO 1.A. Write load_startup_settings(filename), modeling how a real program reads its saved settings the moment it starts up.

💼 Interview Prep

.read() vs. .readlines()

Find # TODO 1.B. Write explain_read_vs_readlines(), explaining the difference between the two.

Topic 2: Writing to Files

1 Writing multiple lines

Find # TODO 2.1. Write save_lines(filename, lines), opening in "w" mode and writing each line with its own "\n".

2 Appending without erasing

Find # TODO 2.2. Write append_line(filename, line), opening in "a" mode to add one more line without erasing what's there.

3 Overwriting on purpose

Find # TODO 2.3. Write overwrite_file(filename, text), opening in "w" mode to erase existing content and write new text.

4 Writing numbered lines

Find # TODO 2.4. Write write_numbered_lines(filename, items), writing each item prefixed with its 1-based position.

5 Debug the Code

Find # TODO 2.5. This function is meant to accumulate a log across multiple calls, but it opens in "w" mode instead of "a" mode each time. Fix it.

💼 Scenario

Appending to a shared audit log

Find # TODO 2.A. Write record_audit_event(filename, username, action) for a security log that must never lose a prior entry.

💼 Interview Prep

"w" vs. "a" in production

Find # TODO 2.B. Write explain_w_vs_a_risk(), explaining the real-world risk of mixing up the two.

Topic 3: File Modes & Paths

1 Summarizing the core modes

Find # TODO 3.1. Write make_mode_summary(), returning a dict describing all four core modes: "r", "w", "a", "r+".

2 Read-modify-write with "r+"

Find # TODO 3.2. Write increment_counter_file(filename), using "r+" mode and file.seek(0) to read-then-overwrite a stored number.

3 Relative vs. absolute paths

Find # TODO 3.3. Write describe_path_kind(path), returning "absolute" or "relative" based on the path's shape.

4 Being explicit about mode

Find # TODO 3.4. Write read_with_explicit_mode(filename), opening with the explicit "r" mode instead of relying on the default.

5 Debug the Code

Find # TODO 3.5. This function opens a file in "w" mode when it needed "r+" to read-then-update without erasing first. Fix it.

💼 Scenario

"It works on my machine"

Find # TODO 3.A. Write explain_relative_path_bug(cwd, script_folder), explaining why a relative path can fail depending on where a script is run from.

💼 Interview Prep

Why not always use absolute paths?

Find # TODO 3.B. Write explain_absolute_path_tradeoff(), explaining why absolute paths aren't just "the safer default".

Topic 4: The csv Module

1 Reading rows as lists

Find # TODO 4.1. Write read_csv_rows(filename), using csv.reader to return a list of row-lists.

2 Reading rows as dictionaries

Find # TODO 4.2. Write read_csv_as_dicts(filename), using csv.DictReader to return a list of row-dictionaries.

3 Summing a numeric column

Find # TODO 4.3. Write total_sales_value(filename), summing a numeric column with csv.DictReader.

4 Writing rows with csv.writer

Find # TODO 4.4. Write write_products_csv(filename, products), using csv.writer with newline="" to export rows.

5 Debug the Code

Find # TODO 4.5. This csv.DictWriter call forgot to pass newline="" when opening the file. Fix it.

💼 Scenario

Importing a spreadsheet export

Find # TODO 4.A. Write find_expensive_products(filename, minimum_price), filtering an exported CSV by a price threshold.

💼 Interview Prep

Why not just .split(",")?

Find # TODO 4.B. Write explain_csv_module_value(), explaining why production code uses the csv module instead of hand-splitting lines.

Topic 5: Handling File-Related Exceptions

1 Catching a missing file

Find # TODO 5.1. Write read_safely(filename), catching FileNotFoundError and returning None.

2 Using the exception's own message

Find # TODO 5.2. Write read_safely_with_message(filename), catching FileNotFoundError as e and returning a message built from e.

3 Falling back to a default

Find # TODO 5.3. Write load_or_default(filename, default_text), catching FileNotFoundError and returning a fallback value.

4 Handling two different file errors

Find # TODO 5.4. Write open_for_either_error(filename), using separate except FileNotFoundError and except PermissionError blocks.

5 Debug the Code

Find # TODO 5.5. This function's except clause catches the wrong exception type entirely, so a genuinely missing file still crashes the program. Fix it.

💼 Scenario

Defensive startup loader

Find # TODO 5.A. Write load_user_preferences(filename) for an app that must never crash just because a settings file doesn't exist yet.

💼 Interview Prep

Check first, or just try it?

Find # TODO 5.B. Write explain_check_first_vs_try_it(), explaining why Python code usually prefers catching FileNotFoundError over checking existence first.

Topic 6: Bringing It Together — File & CSV Processing in Production

1 Counting matching lines defensively

Find # TODO 6.1. Write count_error_lines(log_filename), defensively counting "ERROR" lines in a log file.

2 Exporting a summary report

Find # TODO 6.2. Write export_summary_csv(counts, report_filename), exporting a dict of counts as a CSV report.

3 Counting multiple categories

Find # TODO 6.3. Write count_log_levels(log_filename), counting how many lines match each of several log levels.

4 Merging multiple CSV files

Find # TODO 6.4. Write merge_csv_reports(filenames, output_filename), defensively merging multiple CSV files that might not all exist into one combined report.

5 Debug the Code

Find # TODO 6.5. This function never actually catches FileNotFoundError, so a missing input file crashes the whole function instead of returning a safe fallback. Fix it.

💼 Scenario

Nightly batch report job

Find # TODO 6.A. Write run_nightly_report(log_filename, report_filename), combining defensive reading, log processing, and a CSV export into one real batch-job pattern.

💼 Interview Prep

The production file-processing pattern

Find # TODO 6.B. Write explain_production_file_pattern(), describing the overall pattern real production code uses for file and CSV processing.

Checking your work Compare your output against solution.py. Your exact wording doesn't need to match — the goal is that your program runs without errors and does what each TODO asks. A few TODOs (like Topic 3.2 and 3.5) write to small helper files in this same folder — that's expected, and running the script again should still produce correct results.
← Exercises Challenges →