Build a CSV Parser from Scratch with Corruption Handling
StringsModel answerLast updated
Write a from-scratch CSV tokenizer and data structure for downstream consumers, then extend it to handle rows with missing or extra fields.
You're building a data pipeline component. Your team receives telemetry data as a raw CSV string and needs to parse it into a structure that other engineering teams can query and consume. You cannot use a CSV library or dataframe loader—the tokenizer and data structure must be written from scratch.
You'll be given a sample input like this:
vehicle_id,timestamp,speed_mps,note
av-17,2024-03-01T10:00:00Z,12.5,"stopped, then resumed"
av-22,2024-03-01T10:00:01Z,8.0,
Part 1: Core Parser
Write a parser that processes the raw string and exposes a clean interface for downstream teams. Design both the parsing logic and the API consumers will use to access rows and fields.
Before coding, clarify:
- Can fields contain quoted delimiters and line breaks?
- Should you infer types, or return everything as strings?
- How will consumers access the data—by row iteration, column extraction, or lookup?
- What's the expected payload size?
Your solution should handle:
- Quoted fields that may contain commas, newlines, or escaped quotes (
"") - Empty fields versus missing fields
- Trailing newlines and different line-ending styles (LF, CRLF)
- The header row
Part 2: Corruption Recovery
Real-world payloads sometimes contain corrupted rows. The header is always correct, but data rows may have too few or too many fields, or an unterminated quote.
Extend your parser so corrupted rows don't crash the parse or silently misalign data into the wrong columns. Decide on a policy: should bad rows be dropped, preserved with gaps marked, or cause the entire parse to fail? Consumers need to know which rows failed and why.
Handle:
- Rows with fewer fields than the header declares
- Rows with more fields than expected
- Diagnostic information: line number and failure reason
- Isolation: one bad row shouldn't corrupt adjacent rows
Hints
Hint 1
State-machine tokenizing lets you track whether you're inside or outside quotes, handling escaped quotes and embedded delimiters correctly.
Hint 2
Consider returning a structure with methods like get_row(i), get_column(name), and iter_rows() so consumers can access data the way they need without coupling to your internal representation.
Hint 3
For corruption handling, validate row width immediately after tokenizing each line, and decide whether to collect errors in a list, raise on first failure, or skip bad rows with logging.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem tests string parsing fundamentals, API design, and error recovery. The key is recognizing that a correct CSV tokenizer is a small state machine, not a series of splits, and that the downstream interface matters as much as the internal representation.
Part 1: Parsing Well-Formed Input
Tokenizing. A naive approach splits on commas, but that breaks when a field is quoted and contains a delimiter or newline. The correct strategy is a character-by-character scan with two states: inside quotes and outside quotes. When outside, a comma ends the current field and a newline ends the row. When inside, those characters are literal, and only a quote followed by another quote represents an escaped quote; a quote followed by a delimiter or newline closes the field.
Data structure. Store rows as a list of string lists: [header, row1, row2, ...]. Wrap this in a class that exposes methods like get_row(index), get_column(name), and iter_rows() so consumers don't depend on the internal layout. This keeps the API stable if you later switch to a columnar format or add indexing.
Edge cases. Handle trailing newlines (common in file exports), CRLF versus LF, empty fields (two consecutive commas), and fully blank lines between data rows.
Complexity. Tokenizing is O(n) in the length of the input string, with O(rows × cols) space for the parsed result. A streaming parser that yields rows one at a time would use O(cols) space, useful for large payloads, but the problem statement suggests the whole result fits in memory.
Part 2: Handling Corruption
Detection. After tokenizing a row, check its field count against the header width. A mismatch indicates corruption.
Policy. Three reasonable choices:
- Fail fast: raise an exception on the first bad row, with line number and reason.
- Skip and log: drop corrupted rows but collect diagnostics (line number, expected vs. actual field count) in a separate error list returned alongside the valid data.
- Preserve with markers: keep the row and pad short rows with
Noneor trim long rows, flagging them as corrupt.
The best choice depends on the consumer. If downstream code requires complete data, fail fast. If occasional loss is acceptable and visibility matters, skip and log. For this problem, skip and log balances robustness with transparency.
Isolation. Reset parser state after each newline so a corrupted row (for example, an unterminated quote that runs to end-of-string) doesn't cascade into the next row. One strategy: if a quote is still open at the end of a line and the next character is a newline, treat it as corrupt rather than continuing the field.
Reporting. Return a tuple (data, errors) where errors is a list of {"line": int, "reason": str, "field_count": int} objects. This gives consumers enough context to log or alert without coupling them to your internal parser state.
Code
class CSVData:
def __init__(self, rows, errors=None):
"""
rows: list of lists, first row is header
errors: list of dicts with keys 'line', 'reason', 'field_count'
"""
self.rows = rows
self.errors = errors or []
self.header = rows[0] if rows else []
self._col_index = {name: i for i, name in enumerate(self.header)}
def get_row(self, index):
"""Return row by zero-based index (0 is header)."""
return self.rows[index]
def get_column(self, name):
"""Return all values for a named column, excluding header."""
if name not in self._col_index:
raise KeyError(f"Column '{name}' not found")
col_idx = self._col_index[name]
return [row[col_idx] for row in self.rows[1:] if len(row) > col_idx]
def iter_rows(self, skip_header=True):
"""Iterate over data rows."""
start = 1 if skip_header else 0
return iter(self.rows[start:])
def row_count(self):
return len(self.rows) - 1 # exclude header
def parse_csv(raw: str, skip_corrupted=True):
"""
Parse a raw CSV string with RFC 4180-style quoting.
Args:
raw: the CSV string
skip_corrupted: if True, drop rows with wrong field count and log errors;
if False, raise on first corrupted row
Returns:
CSVData object with rows and error list
"""
rows = []
errors = []
lines = raw.replace('\r\n', '\n').split('\n')
expected_width = None
for line_num, line in enumerate(lines, start=1):
# Skip blank lines
if not line.strip():
continue
fields = _tokenize_line(line)
# First non-blank line is the header
if expected_width is None:
expected_width = len(fields)
rows.append(fields)
continue
# Validate field count
if len(fields) != expected_width:
error = {
"line": line_num,
"reason": f"Expected {expected_width} fields, got {len(fields)}",
"field_count": len(fields)
}
if skip_corrupted:
errors.append(error)
continue
else:
raise ValueError(f"Line {line_num}: {error['reason']}")
rows.append(fields)
return CSVData(rows, errors)
def _tokenize_line(line: str):
"""Tokenize a single CSV line, respecting quoted fields."""
fields = []
current = []
in_quotes = False
i = 0
while i < len(line):
char = line[i]
if in_quotes:
if char == '"':
# Check if it's an escaped quote
if i + 1 < len(line) and line[i + 1] == '"':
current.append('"')
i += 2
continue
else:
# End of quoted field
in_quotes = False
i += 1
else:
current.append(char)
i += 1
else:
if char == '"':
in_quotes = True
i += 1
elif char == ',':
fields.append(''.join(current))
current = []
i += 1
else:
current.append(char)
i += 1
# Append the last field
fields.append(''.join(current))
return fields
Walkthrough
Given:
vehicle_id,timestamp,speed_mps,note
av-17,2024-03-01T10:00:00Z,12.5,"stopped, then resumed"
av-22,2024-03-01T10:00:01Z,8.0,
- Line 1 tokenizes to
["vehicle_id", "timestamp", "speed_mps", "note"], stored as header with width 4. - Line 2: the tokenizer sees a quote before "stopped", accumulates characters including the comma and space, sees the closing quote, then the final comma and newline. Fields:
["av-17", "2024-03-01T10:00:00Z", "12.5", "stopped, then resumed"]. Width matches, row added. - Line 3: final field is empty (trailing comma). Fields:
["av-22", "2024-03-01T10:00:01Z", "8.0", ""]. Width matches, row added.
If line 3 were av-22,2024-03-01T10:00:01Z,8.0 (only three fields), the parser would log an error and skip the row if skip_corrupted=True, or raise if False.
Common Mistakes
- Splitting on commas without respecting quotes, breaking on the sample input.
- Forgetting to handle escaped quotes (
""inside a quoted field). - Silently padding short rows with empty strings, which hides data corruption.
- Returning raw lists without an API, forcing every consumer to reimplement column lookup.
- Not testing edge cases: trailing newline, CRLF, blank lines, empty fields.
Complexity
- Time: O(n) where n is the length of the raw string.
- Space: O(r × c) for r rows and c columns, plus O(e) for error records.
A streaming version that yields rows one at a time would reduce space to O(c), useful for multi-gigabyte payloads.