Coding Challenges: File Handling & CSV
8 HackerRank-style challenges, auto-graded right in your browser —
no setup required. Write your function in the code box, then click
Run Tests to check it against a set of test cases
(including edge cases). Stuck? Every challenge has a
Show Solution reveal at the bottom. Only uses what
Chapters 1-13 have covered so far — everything through custom
exception classes, and this chapter's own toolkit: string processing of
file-shaped content and the csv module. No other class
besides a custom exception, and no import beyond
math/datetime/random/csv.
open()
a file from, so every challenge here takes the file's or CSV's
contents as a plain string argument — exactly what
you'd already have in hand after a real with open(...) as file:
content = file.read() call. For the CSV challenges,
csv.reader and csv.DictReader both accept any
iterable of strings, not just an open file object — so
csv.DictReader(csv_content.splitlines()) works exactly the
same way csv.DictReader(file) would on a real file.
1 Count Matching Lines Easy
Write a function count_lines_containing(content, keyword) that takes the contents of a log file as a string, splits it into lines, and returns how many lines contain keyword anywhere in them.
content may be an empty string; keyword matching is case-sensitive and can appear anywhere in the line.
count_lines_containing("a\nb\nc", "a") → 1count_lines_containing("", "ERROR") → 0
Show Solution
def count_lines_containing(content, keyword):
count = 0
for line in content.splitlines():
if keyword in line:
count += 1
return count
2 Extract Lines by Prefix Easy
Write a function extract_lines_with_prefix(content, prefix) that takes file content as a string and returns a list of every line that starts with prefix, in the order they appear.
content may be an empty string; no line may match, in which case return an empty list.
extract_lines_with_prefix("apple\nbanana\napricot", "ap") → ["apple", "apricot"]extract_lines_with_prefix("apple\nbanana", "z") → []
Show Solution
def extract_lines_with_prefix(content, prefix):
matches = []
for line in content.splitlines():
if line.startswith(prefix):
matches.append(line)
return matches
3 Count Error Types Medium
Write a function count_error_types(log_content) that takes a server log's content as a string. For every line containing "ERROR", extract the message that comes after it (split the stripped line on "ERROR" once, take the second part, and .strip() it), then return a dict counting how many times each distinct error message occurred.
log_content may be an empty string, or contain no "ERROR" lines at all, in which case return {}.
count_error_types("ERROR bad\nERROR bad") → {"bad": 2}count_error_types("INFO all good") → {}
Show Solution
def count_error_types(log_content):
counts = {}
for line in log_content.splitlines():
if "ERROR" in line:
message = line.strip().split("ERROR", 1)[1].strip()
counts[message] = counts.get(message, 0) + 1
return counts
4 Parse CSV Content Medium
Write a function parse_csv_content(csv_content) that takes the contents of a CSV file as a string and returns a list of dictionaries, one per data row, using csv.DictReader(csv_content.splitlines()) — DictReader accepts any iterable of strings, not just an open file object, so splitting the content into lines first works exactly the way reading from a real file would.
parse_csv_content("a,b\n1,2") → [{"a": "1", "b": "2"}]parse_csv_content("a,b") → []
Show Solution
import csv
def parse_csv_content(csv_content):
reader = csv.DictReader(csv_content.splitlines())
return [dict(row) for row in reader]
5 Sum a CSV Column Medium
Write a function sum_csv_column(csv_content, column_name) that parses csv_content with csv.DictReader(csv_content.splitlines()), converts row[column_name] to a float for every row, and returns the total, rounded to 2 decimal places.
0.0.
sum_csv_column("qty\n1\n2\n3", "qty") → 6.0sum_csv_column("qty\n0", "qty") → 0.0
Show Solution
import csv
def sum_csv_column(csv_content, column_name):
reader = csv.DictReader(csv_content.splitlines())
total = 0.0
for row in reader:
total += float(row[column_name])
return round(total, 2)
6 Find the Max Row Medium
Write a function find_max_row(csv_content, column_name, key_column) that parses csv_content with csv.DictReader, finds the row where float(row[column_name]) is largest, and returns that row's row[key_column] value.
find_max_row("name,score\nA,10\nB,99\nC,5", "score", "name") → "B"find_max_row("name,score\nA,10", "score", "name") → "A"
Show Solution
import csv
def find_max_row(csv_content, column_name, key_column):
reader = csv.DictReader(csv_content.splitlines())
best_key = None
best_value = None
for row in reader:
value = float(row[column_name])
if best_value is None or value > best_value:
best_value = value
best_key = row[key_column]
return best_key
7 Safe Batch Parse Medium
Write a function safe_parse_int_lines(content) that splits content into lines, skips any blank line, and tries to convert each remaining line (after .strip()) to an int inside a try/except ValueError — appending successful conversions to a successes list and failing raw lines to a failures list. Return {"successes": successes, "failures": failures}.
content may be empty or contain only blank lines, in which case both lists are empty.
safe_parse_int_lines("1\n2\nabc\n4\nxyz") → {"successes": [1, 2, 4], "failures": ["abc", "xyz"]}safe_parse_int_lines("") → {"successes": [], "failures": []}
Show Solution
def safe_parse_int_lines(content):
successes = []
failures = []
for line in content.splitlines():
stripped = line.strip()
if stripped == "":
continue
try:
successes.append(int(stripped))
except ValueError:
failures.append(stripped)
return {"successes": successes, "failures": failures}
8 Count Rows by Category Medium
Write a function csv_row_count_by_category(csv_content, category_column) that parses csv_content with csv.DictReader and returns a dict counting how many rows fall into each distinct value of row[category_column].
{}.
csv_row_count_by_category("name,dept\nA,eng\nB,sales\nC,eng", "dept") → {"eng": 2, "sales": 1}csv_row_count_by_category("name,dept", "dept") → {}
Show Solution
import csv
def csv_row_count_by_category(csv_content, category_column):
reader = csv.DictReader(csv_content.splitlines())
counts = {}
for row in reader:
category = row[category_column]
counts[category] = counts.get(category, 0) + 1
return counts