Parse CSV by Hand (RFC 4180)

medium
Unit 15 · Parsing I0/2 to milestone

CSV looks trivial until a field contains a comma, a quote or a newline. Implement a parser without the csv module:

parse_csv(text, delimiter=",") returns a list of rows (lists of strings):

  • Rows end at \n or \r\n. A final trailing newline doesn't create an extra empty row.
  • A field that starts with " is quoted: it may contain delimiters and newlines, "" inside it means a literal quote, and it ends at the next lone ". An unterminated quoted field raises ValueError.
  • A " in the middle of an unquoted field is just a character.
  • An empty line is a row with one empty field: [""].

Then implement to_csv(rows, delimiter=","): quote a field (doubling inner quotes) only if it contains the delimiter, a quote, \n or \r. Join fields with the delimiter and rows with \n.

#parsing#csv#state-machines2 visible + 2 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Parse CSV by Hand (RFC 4180) · TechGradify