JESKO GARAGE All topicsViva questions ▶ Open the practice garage

Python FILE HANDLING (text & CSV) and ERROR HANDLING: 13 practice problems

UNIT 2 of the free Python for AI course. Read the short theory, then solve the problems below with instant tests. Python runs in your browser.

▶ Practise FILE HANDLING (text & CSV) and ERROR HANDLING nowAll topics

Theory: FILE HANDLING (text & CSV) and ERROR HANDLING in Python

THEORY — FILES
--------------
* open(path, mode, encoding="utf-8")   modes: "r" read (default) · "w" write (ERASES first!) ·
  "a" append · "x" create (fails if exists) · "b" binary ("rb", "wb") · "+" read+write
* ALWAYS use `with` — the file is closed automatically, even if an error happens:
      with open("notes.txt", "w", encoding="utf-8") as f:
          f.write("line 1\n")                # write() does NOT add a newline for you
          f.writelines(["a\n", "b\n"])
      with open("notes.txt", encoding="utf-8") as f:
          text = f.read()          # whole file as ONE string
          # f.readline()  -> next line;   f.readlines() -> list of lines (with \n)
          # for line in f: ...       -> line by line, memory-friendly for big files
  line.rstrip("\n") / line.strip() to remove the newline.
* Paths: os.path.join("data", "a.txt") (portable), os.path.exists(p), pathlib.Path(p).read_text()

THEORY — CSV (comma-separated values)
-------------------------------------
      import csv
      with open("m.csv", newline="", encoding="utf-8") as f:      # newline="" is required!
          for row in csv.reader(f): ...          # row = list of STRINGS
          for row in csv.DictReader(f): ...      # row = dict {header: value-string}
      with open("out.csv", "w", newline="", encoding="utf-8") as f:
          w = csv.writer(f);  w.writerow(["name", "marks"]);  w.writerows(rows)
          w = csv.DictWriter(f, fieldnames=[...]);  w.writeheader();  w.writerows(list_of_dicts)
  Everything read from CSV is a STRING -> convert with int()/float().  The csv module correctly
  handles commas inside quotes ("Pune, India") — never split CSV lines with .split(",") yourself.

THEORY — ERRORS & EXCEPTIONS
----------------------------
* SyntaxError: code can't be parsed (never runs).  EXCEPTIONS happen while running:
  ValueError (right type, bad value: int("x")), TypeError ("a" + 1), KeyError, IndexError,
  ZeroDivisionError, FileNotFoundError, AttributeError, NameError, PermissionError.
      try:
          risky()
      except (ValueError, TypeError) as e:     # catch SPECIFIC exceptions
          print("bad input:", e)
      except FileNotFoundError:
          ...
      else:      # runs only if NO exception
          ...
      finally:   # ALWAYS runs (cleanup)
          ...
* raise ValueError("message")      — signal an error yourself
* Custom exceptions:  class InsufficientFundsError(Exception): pass
* Never use a bare `except:` — it hides bugs (even Ctrl+C).
* EAFP ("easier to ask forgiveness": try it, catch failure) vs LBYL ("look before you leap": check
  first with if). Python style prefers EAFP.

13 FILE HANDLING (text & CSV) and ERROR HANDLING practice problems

1. Mini `wc` Command — read a text file

Easy2 ways to solve
📤 OUTPUT: return a tuple (lines, words, characters) like the Unix `wc` tool. Use `return`, not print().
Return a tuple (lines, words, characters) like the Unix `wc` tool.
    file "hello world\nbye\n" -> (2, 3, 16)
Solve “Mini `wc` Command — read a text file” in your browser →

2. Application Log — append mode

Easy1 way to solve
📤 OUTPUT: return the line you wrote as a str, e.g. '[3] user logged in'. Use `return`, not print().
Real world: Apps keep a log file and add one numbered line per event.
Append the line "[n] message" where n = (number of existing lines) + 1. If the file doesn't
exist yet, n = 1. Return the line you wrote (without the newline).
    append_log(p, "started") -> "[1] started";  append_log(p, "stopped") -> "[2] stopped"
Solve “Application Log — append mode” in your browser →

3. Search Inside a File — line numbers

Easy2 ways to solve
📤 OUTPUT: return the 1-based numbers of lines containing `word` (case-insensitive). Use `return`, not print().
Return the 1-based numbers of lines containing `word` (case-insensitive).
    file "Error: x\nok\nerror again\n", "ERROR" -> [1, 3]
Solve “Search Inside a File — line numbers” in your browser →

4. Expense Tracker — csv.DictReader + dict totals

Medium2 ways to solve
📤 OUTPUT: return a dict {category: total}, e.g. {'food': 300.0, 'travel': 100.0}. Use `return`, not print().
CSV columns: date,category,amount.  Return {category: total amount as float rounded to 2}.
    date,category,amount
    2024-01-01,food,250.50
    2024-01-02,travel,100
    2024-01-05,food,49.50
    -> {"food": 300.0, "travel": 100.0}
Solve “Expense Tracker — csv.DictReader + dict totals” in your browser →

5. Export to CSV — csv.DictWriter

Easy2 ways to solve
📤 OUTPUT: return the number of DATA rows written, an int. Use `return`, not print().
rows: non-empty list of dicts with the same keys. Header = keys of the first row (in order).
Write the file and return the number of DATA rows written.
Solve “Export to CSV — csv.DictWriter” in your browser →

6. Filter Rows Into a New CSV — read + write

Medium2 ways to solve
📤 OUTPUT: return how many rows were kept, an int. Use `return`, not print().
Real world: Export only the students who scored at least 75.
Copy the header and every row where float(row[column]) >= min_value. Return how many rows were kept.
Solve “Filter Rows Into a New CSV — read + write” in your browser →

7. Read Without Crashing — try/except FileNotFoundError

Easy2 ways to solve
📤 OUTPUT: return the file content, or the string "FILE NOT FOUND". Use `return`, not print().
Return the file content, or the string "FILE NOT FOUND".
Solve “Read Without Crashing — try/except FileNotFoundError” in your browser →

8. Validate Age Input — raise ValueError with a message

Easy1 way to solve
📤 OUTPUT: return int(text). Raise ValueError("Age must be a number") if it isn't an integer,. Use `return`, not print().
Return int(text). Raise ValueError("Age must be a number") if it isn't an integer,
and ValueError("Age must be between 0 and 150") if out of range.
    parse_age("25") -> 25
Solve “Validate Age Input — raise ValueError with a message” in your browser →

9. Bank Withdrawal — custom exception

Easy1 way to solve
📤 OUTPUT: return the new balance as a number, e.g. 300; RAISE the errors described. Use `return`, not print().
amount <= 0 -> raise ValueError("Invalid amount")
amount > balance -> raise InsufficientFundsError(f"Need {amount - balance} more")
otherwise return the new balance.
    withdraw(500, 200) -> 300
Solve “Bank Withdrawal — custom exception” in your browser →

10. Dirty Sensor Data — try/except inside a loop

Medium2 ways to solve
📤 OUTPUT: return a tuple, e.g. (20.0, 2). Use `return`, not print().
values may contain numbers, numeric strings ("12.5"), junk ("err", None).
Return (average of valid numbers rounded to 2, number skipped). No valid values -> (0.0, skipped).
    robust_average([10, "20", "err", None, 30.0]) -> (20.0, 2)
Solve “Dirty Sensor Data — try/except inside a loop” in your browser →

11. .env / Config File Parser

Medium2 ways to solve
📤 OUTPUT: return a dict of settings, e.g. {'HOST': 'localhost'}. Use `return`, not print().
Lines look like  KEY=value. Ignore blank lines and lines starting with #. Strip spaces around
key and value. Values containing "=" keep everything after the FIRST "=". Return a dict.
    "# db\nHOST = localhost\nURL=a=b\n\n" -> {"HOST": "localhost", "URL": "a=b"}
Solve “.env / Config File Parser” in your browser →

12. Payroll Export — interview at an HR-software company

Project1 way to solve
📤 OUTPUT: return a tuple (rows_written, bad_line_numbers), e.g. (4, [3, 5, 7]). Use `return`, not print().
Interviewer: "HR exports timesheets as CSV. Compute pay, skip bad rows, and write the bank file."
Input CSV columns: name,hourly_rate,hours. Pay = rate * hours; hours ABOVE 40 are paid 1.5x.
Bad rows (missing value, not a number, or negative) are skipped and their LINE NUMBERS recorded
(the header is line 1).
Write out_path with header name,pay and one row per employee sorted by pay DESC (ties by name),
pay formatted with 2 decimals ("23750.00"). Return (rows_written, bad_line_numbers).
Solve “Payroll Export — interview at an HR-software company” in your browser →

13. Stage 13 — Reading the Source File

Compiler1 way to solve
📤 OUTPUT: return a list of (line_no, text) for every line that isn't empty and isn't a comment. Use `return`, not print().
Return a list of (line_no, text) for every line that isn't empty and isn't a comment
(text is stripped; a comment line starts with #). Line numbers start at 1.
A missing file must NOT crash: return [].
Solve “Stage 13 — Reading the Source File” in your browser →

← Modules & external packages CLEAN CODE, DEBUGGING, JSON & WEB APIs (requests) →