Fix a Buggy Python Table-to-CSV Function
StringsModel answerLast updated
Audit a short Python function that flattens rows into CSV text, list its correctness and performance flaws with triggering inputs, and rewrite it safely and efficiently.
A teammate has submitted the following Python helper in a pull request. It is supposed to convert a table, represented as a list of rows where each row is a list of cells, into CSV text.
def to_csv(table):
output = ""
for row in table:
for cell in row:
output += cell
output += ","
output += "\n"
return output
Review it as you would in a real code review.
- List every problem you can find. For each one, give a concrete input that triggers it and explain what goes wrong (what the function returns versus what a correct CSV would look like).
- Write a corrected version of the function.
- Describe how you would test the fix, and what you would ask the author before settling on the final behavior.
Assume the output will be read back by a standard CSV parser, for example a spreadsheet or Python's csv module.
Hints
Hint 1
Read back the output of a single row such as ["a", "b"]. How many fields does a parser see on that line, and what is the last character before the newline?
Hint 2
Try cells that are not strings (an int, None, a float), and cells that contain a comma, a double quote or a newline. What does each do to the function, and what rule does CSV define for them?
Hint 3
Think about what += on a str does in a loop over many cells, and whether the whole result must exist in memory at once. The standard library already has a tested CSV writer you can point at a file-like object.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Issues found
1. Trailing delimiter on every line.
The comma is appended after every cell, including the last one. to_csv([["a", "b"]]) returns "a,b,\n", which a parser reads as three fields, the last one empty. Every record gains a phantom column. The delimiter belongs between cells, not after each.
2. Non-string cells crash.
output += cell requires cell to be a str. to_csv([["id", 7]]) raises TypeError: can only concatenate str (not "int") to str. The same happens with None, floats, booleans, dates and so on. The code needs a defined conversion policy (for example None becomes an empty field, everything else goes through str()).
3. No quoting or escaping. CSV (RFC 4180) requires a field to be wrapped in double quotes if it contains the delimiter, a double quote or a line break, and any embedded double quote must be doubled.
[["Smith, John", "NY"]]producesSmith, John,NY,which parses as three fields instead of two.[['say "hi"']]produces an unbalanced quote in the wrong place for strict parsers.[["line1\nline2"]]splits one record into two lines.
This is also a data-integrity and security concern: a cell starting with =, +, - or @ can be interpreted as a formula when opened in a spreadsheet (CSV injection). If the file is user-facing, prefix such cells with a single quote or tab, depending on policy.
4. Quadratic-risk string building.
Strings are immutable in Python. output += cell conceptually creates a new string each time. CPython sometimes optimizes this in place when the reference count is one, but that is an implementation detail, not guaranteed (and does not hold in other interpreters). For a table with N total characters and many cells, the worst case is O(N^2) copying. The fix is to collect pieces in a list and call "".join(...), or better, write incrementally to a stream.
5. Whole result held in memory. Returning a single giant string means a million-row table needs the entire text in memory, plus the input table. For files or HTTP responses, a generator or a writer on a file object keeps memory flat.
6. Smaller points.
- Line endings: RFC 4180 specifies CRLF; the code emits LF. Decide based on the consumer, and when writing to a file, open it with
newline=""so Python does not translate line endings again. - Encoding: choose one (UTF-8, perhaps with a BOM if Excel is a target) and state it.
- Ragged rows are written as-is. That is valid CSV, but many consumers expect a fixed width, so decide whether to validate or pad.
- No header handling, no way to change the delimiter.
Fixed version
Prefer the standard library, which already implements quoting, doubling and line terminators correctly:
import csv
import io
def to_csv(table, delimiter=","):
buf = io.StringIO(newline="")
writer = csv.writer(buf, delimiter=delimiter,
quoting=csv.QUOTE_MINIMAL,
lineterminator="\r\n")
for row in table:
writer.writerow("" if c is None else c for c in row)
return buf.getvalue()
csv.writer calls str() on non-string cells, so ints and floats work, and it quotes fields containing the delimiter, quotes or newlines.
For large data, skip the in-memory string and stream:
def write_csv(table, fileobj):
writer = csv.writer(fileobj, lineterminator="\r\n")
for row in table:
writer.writerow("" if c is None else c for c in row)
with open("out.csv", "w", newline="", encoding="utf-8") as f:
write_csv(rows_iterable, f)
Time is O(total characters), memory is O(one row) when streaming.
If a library is not allowed, a hand-written equivalent is:
def to_csv(table):
def esc(v):
s = "" if v is None else str(v)
if any(ch in s for ch in ',"\r\n'):
s = '"' + s.replace('"', '""') + '"'
return s
return "".join(",".join(esc(c) for c in row) + "\r\n" for row in table)
Testing
- Round trip: write with
to_csv, read withcsv.reader, and assert the result equals the input (after stringification). Property-based tests (for example Hypothesis) with random text including commas, quotes,\n,\rand unicode catch most escaping bugs. - Table of examples: empty table, a row with no cells, a single empty-string cell (should be
""or an empty line, which is ambiguous, so test the parser's view),None, integers, floats, embedded quote, comma and newline. - Field count: assert each parsed row has the same length as the input row.
- Performance: time a table with 1M cells to confirm linear growth, and check peak memory with the streaming version.
Questions to ask the author
- Who consumes the file (Excel, a service, a standard parser), and which line ending, encoding and delimiter do they expect?
- Which cell types occur, and how should
None, dates and booleans be rendered? - Are rows guaranteed to have the same length, and is there a header?
- How large can the data be, and is it written to disk or a network response (which favors streaming)?
- Is spreadsheet formula injection a concern for this export?
Common mistakes in answers
- Only noting the trailing comma and missing quoting or non-string handling.
- Fixing the trailing comma with
output[:-1]slicing, which is still quadratic and breaks on empty rows. - Using
",".join(row)and believing it solves escaping (it does not, and it still fails on non-strings). - Reimplementing quoting by hand without mentioning that the standard
csvmodule exists. - Opening the output file without
newline="", producing doubled\r\r\non Windows.