Skip to content
CLEARER IDEAS. BETTER EXECUTION.PROGRAMMING · CREATIVE AI · WORKFLOWS
Menu & topics
Programming

CSV Exports Have Two Consumers: Keep Machine Data and Review Copies Separate

Original code, local tests and clear limits for Python CSV export review copy formula text. Separate observed results from proposed integration.

An oak card organizer with three columns of blank cards, a blue pencil and a print of a small teal ceramic house
An oak card organizer with three columns of blank cards, a blue pencil and a print of a small teal ceramic house.
The short answerA machine export should preserve the input strings; a review copy can deliberately transform them under a separate contract. This example tests CSV serialization and an apostrophe-prefixed review representation in Python only. It does not prove safe formula handling in Excel, LibreOffice or any spreadsheet application.

Name the consumer before changing its values

The source row in our first fixture contains the string =1+2. In machine mode, export_rows serializes it and Python's csv.reader reads back exactly =1+2. In review mode, the same reader returns an apostrophe followed by =1+2. Those are deliberately different strings. Neither test opens a spreadsheet or executes a formula. The question this project answers is how to keep a transformed inspection artifact separate from the original machine data, without mistaking a formatting choice for evidence of application-specific safety.

This distinction matters in a proposed image-project catalog that exports labels, prompts or filenames. An ingestion program may require the exact stored strings, while a review process may want a deliberately marked representation. If both downloads have the same name and undocumented rules, someone can upload the transformed copy into an importer expecting original values. Our example makes the difference explicit with one review flag and retained source rows. It does not claim that an apostrophe is the best inspection interface or a portable spreadsheet formula defense.

The lead photograph shows an oak card organizer, blank cards, a blue pencil and a teal ceramic-house print. It illustrates a small catalog review task, not an exported spreadsheet or measured human workflow. Actual outputs are machine.csv, review.csv and contract.json under the code example's outputs directory. The test evidence concerns Python text serialization and roundtrips through csv.reader. Keeping those artifacts separate prevents a photograph or a file extension from being presented as proof that a particular spreadsheet application interpreted the data as intended.

Read the row contract before the writer loop

The final exporter accepts an outer sequence of rows, with each supplied row required to be a list or tuple. It rejects a string row or an iterator row explicitly. This boundary was added after examining how the original validation could consume an iterator before the later write expression used it. Instead of claiming arbitrary row-iterator support, this small wrapper now declares a narrower input shape. The helper still needs review before use in a larger importer; it does not validate a catalog schema or infer which column each string represents.

Spreadsheet software can interpret some imported cell contents as formulas. Quoting fields alone is not a universal defense, and behavior across applications and reopening can differ. OWASP CSV Injection

Within each accepted row, the function checks that every cell is a string before writing that row. A non-string cell raises TypeError. This is per-row validation inside the loop, not an initial pass that validates the entire dataset before any internal writing. The output buffer is StringIO, and the function returns its text only after the loop finishes. If a later row fails, the function raises rather than returning a completed export. It is not an external streaming writer or an atomic filesystem save.

The writer uses QUOTE_ALL and a newline line terminator. Every field is quoted in the serialized CSV representation, but quotes are structural delimiters, not part of the original cell value returned by csv.reader. StringIO contains Python text rather than encoded file bytes. The helper does not choose UTF-8, add a byte-order mark or write a file. Our retained output-generation step explicitly used UTF-8 outside the helper; that separate choice must not be retroactively attributed to every in-memory roundtrip test.

csv_exports.py

import csv
from io import StringIO

def export_rows(rows,review=False):
    output=StringIO(newline='')
    writer=csv.writer(output,quoting=csv.QUOTE_ALL,lineterminator='\n')
    for row in rows:
        if not isinstance(row,(list,tuple)):
            raise TypeError('Expected a list or tuple row')
        if any(not isinstance(value,str) for value in row):
            raise TypeError('This fixture exports string cells only')
        writer.writerow(["'"+value if review else value for value in row])
    return output.getvalue()

The original 8 methods were rerun after the row-contract guard, and 6 further methods passed. Environment: Python 3.12.3 on Windows. Actual machine/review CSV files and their source rows are retained. No spreadsheet application, formula execution, save-and-reopen behavior or portable safety sanitizer was tested.

Machine and review modes make different promises

In machine mode, the writer receives each original string. The fixture =1+2 therefore remains that literal string when parsed by the Python reader. The test does not claim that every program importing the CSV will keep it as text rather than interpreting it. Automated consumers should use their specified parsing and type rules. The contract demonstrated here is preservation through the chosen Python serializer and reader, not preservation through a spreadsheet application whose import behavior was never run in this experiment.

In review mode, the list expression adds one apostrophe to every cell, including plain text and an empty string. There is no detector that classifies formula-like values before deciding what to modify. test_review_adds_apostrophe_to_every_field supplies both =1+2 and plain and expects both to receive the prefix. This uniform rule makes the transformation easy to describe, but it also makes the result unsuitable as a silent replacement for original catalog data. A machine consumer expecting plain now receives a different value.

An empty cell becomes a cell containing one apostrophe in review mode. That is not a missing value or an unchanged blank. The caller must decide whether such a representation helps its actual review process. We have not measured reviewer preference or opened the result in a graphical application. The point is to expose the transformation as a separate artifact with a separate contract, so that an importer does not accidentally treat a deliberately changed cell as the authoritative label or prompt stored by the project.

Commas, quotation marks and newlines belong inside cells

test_delimiter_and_quote_remain_in_one_cell uses a string containing a comma and a quotation mark. After review serialization and parsing, the reader returns one cell with the prefixed original content. The writer handles CSV quoting for that field. A hand-built string joined with commas would need its own rules to avoid confusing embedded punctuation with column boundaries. Our test is deliberately small enough to inspect the exact input and expected parsed string, rather than claiming that a plausible-looking line proves correct serialization.

A newline inside a field creates another distinction between file layout and records. test_multiline_cell covers a machine-mode field containing a real newline, and the additional test_multiline_review_value covers the prefixed review form. Both are read as one cell by csv.reader. Do not parse these exports by splitting text into physical lines and then splitting each line at commas. That would discard the quoting contract being tested. The helper returns structured CSV text, not a format where every visible line must independently represent one complete catalog row.

The original Arabic test covers the machine representation of صورة. The added Arabic review test checks the same string with the deliberate apostrophe prefix. These are Python string comparisons. They do not inspect a font, bidirectional screen layout or the bytes of every possible encoded file. The retained UTF-8 outputs provide a separate concrete artifact to inspect, but the unit assertions should still be described accurately. Unicode text surviving this Python roundtrip is a narrower observation than universal import compatibility across desktop applications.

An empty row is also different from a row with an empty cell. test_empty_row_differs_from_empty_cell expects an empty row to remain a row with no cells after parsing, while a one-cell empty row gains the apostrophe in review mode. The writer has no field to prefix in the first case. This edge can matter to a proposed importer that requires a fixed number of columns. The serializer does not enforce that schema; it documents the actual output and leaves the caller to reject or interpret empty records explicitly.

What the fourteen methods actually establish

The original eight methods cover formula-like text preservation in machine mode, uniform review prefixes, punctuation in one field, a multiline machine cell, Arabic machine text, the changed empty review cell, unchanged input rows and a non-string cell. Those eight were rerun after adding the list-or-tuple row guard. The current helper hash and run record refer to the final source. The earlier source and results are retained as history so that the new input boundary is not falsely described as having been present in the first implementation.

Six additional methods cover tuple-row acceptance, string-row rejection, iterator-row rejection, empty row versus empty cell, Arabic review text and multiline review text. Together the two suites contain 14 distinct unittest methods. A method can have more than one assertion, so 14 is not an assertion count or a count of spreadsheet environments. Each fixture has an input and expected parsed result. No Excel or LibreOffice session, formula execution, browser view, save-and-reopen workflow or spreadsheet security test is included.

test_source_unchanged checks that the supplied list still contains =1+2 after a review export. That does not make the list immutable or prevent another component from changing it. It only establishes that this function did not replace the original cell in the fixture. This is useful when producing both exports from the same source rows: the first call does not rewrite the input into the review representation before the second call. It is not evidence of thread isolation, a database snapshot or protection against unrelated concurrent changes.

The additional iterator-row rejection deserves a direct explanation rather than a vague robustness claim. The helper checks values and then writes them; supporting one-shot iterators would require preparing a reusable row or redesigning that sequence. Here we chose explicit list and tuple rows and tested the rejection. A caller with generator-based data can materialize its row at a documented boundary before calling this wrapper. We did not benchmark that choice or implement an arbitrary streaming export service; the code remains a small in-memory serializer.

Quoting is a structural contract, not a spreadsheet guarantee

OWASP guidance notes that spreadsheet software can interpret some imported cell contents as formulas and that behavior can differ across applications and reopening. That source supports the reason to avoid calling ordinary quoting a universal formula defense. It does not turn our apostrophe-prefixed representation into a tested safe download. Our tests use csv.reader, which returns strings; they do not exercise the interpretation layer in a spreadsheet. Keep that boundary visible when explaining why the machine and review artifacts differ.

An apostrophe can be part of a chosen consumer contract, but this project does not establish how an arbitrary application will display, retain or later rewrite it. In particular, do not tell reviewers that opening an untrusted CSV is safe merely because our review flag was True. A proposed workflow should use an explicitly tested consumer or a different text-oriented review interface with its own rules. That is a design requirement for the application, not a capability implemented by this helper or proved by a successful Python roundtrip.

Do not recover original data by guessing from a leading apostrophe in an unknown file. A legitimate original string may already begin with that character. The function adds one prefix deliberately; it does not mark the artifact with an authenticated origin or provide an import path that knows which transformation was applied. A proposed system can retain the original source and a separately identified review artifact instead of trying to reconstruct provenance from the first character of each cell. The current code includes no reverse importer.

Inspect the actual three-row output pair

The retained sample dataset has three rows: a formula-like string and plain; Arabic text and a multiline cell; then an empty string and a comma-and-quote cell. The output step calls export_rows twice from that same dataset and writes machine.csv and review.csv with explicit UTF-8 text encoding and newline handling. contract.json retains the source rows and the two encoded file hashes. These are actual local outputs, not a claim that a user opened or accepted either file in a spreadsheet.

To inspect the pair, compare parsed cells rather than the visual width of quoted text. The machine form should reflect the source strings under the specified Python reader, while the review form deliberately adds its prefix to every existing field. A comma in the source remains part of one cell, and an embedded newline remains inside that cell. The empty string and empty row cases are separate from the three-row sample. They appear in the tests so that a reader does not infer schema behavior from the example file alone.

Keep the two output hashes attached to the two files they identify. A different review file hash is expected because the representation changed. It does not prove corruption of the original source rows or identify which consumer should receive the artifact. The hash also says nothing about spreadsheet safety. The sidecar describes why the strings differ, while the original rows and assertions let you check that explanation. Do not replace the source catalog with the review file simply because both exports were generated during the same successful run.

Design download names and manifests for the proposed workflow

A proposed catalog interface can label its downloads Machine data and Review representation and give them different filenames. The label should describe that cell values change in the review representation, rather than promising that it is universally safe for a spreadsheet. Keep the contract visible near the download action. This interface was not built in the experiment, and we did not measure whether users understand the distinction. The local code gives the interface an explicit flag and testable values to explain.

An optional sidecar manifest can identify the contract version, source dataset reference, selected mode and output filename. It can record a row count once the application defines how empty records and schema validation are handled. Do not insert arbitrary metadata lines into a CSV whose machine consumer expects every record to follow one schema. A separate JSON sidecar avoids changing that consumer's record format. Our retained contract.json is a small local example of keeping the transformation explanation outside the CSV, not a deployed audit or tamper-protection system.

The output-writing boundary needs its own checks. The linked staging-file project addresses completed output replacement, while this helper decides what the CSV text contains. A proposed exporter can first build and validate its representation, then hand it to a separately tested writer. An incomplete write and an intentionally prefixed cell are different causes of an unexpected import. Do not describe the StringIO buffer as a filesystem transaction, or assume that a completed file proves its values were the ones the receiving program expected.

Choose a different review representation when the consumer needs it

A proposed text review screen could show original values and annotations in separate columns without changing the stored strings. It might display an empty-value marker, preserve a multiline value visibly, and distinguish a note about formula-like content from the content itself. None of that UI behavior has been implemented or security-tested here. The value of this alternative is the separation it makes explicit: original data can remain original while the review process adds context in a different field instead of overloading one leading character.

If a spreadsheet application is a genuine requirement, identify its version and import procedure and design a separate experiment using representative permitted data. Record what was opened, how the columns were interpreted and whether a later save-and-reopen changes the result. We have not run those steps, and this article supplies no acceptance result for them. The serializer fixtures can be inputs to a future controlled consumer test, but a Python reader success must not be relabeled as the missing application-level evidence.

A machine importer should also know which artifact it accepts. A proposed import endpoint can require the machine contract and retain the original source reference, rather than attempting to strip all apostrophes from an uploaded review copy. Stripping can remove legitimate original content, while accepting a transformed field unchanged can introduce a different label or prompt. We did not build an endpoint or access-control layer. These are specific contract decisions to make around the tested serializer, not features implied by having two local filenames.

Decide whether a header is data under this contract

The helper has no special header branch. If a proposed catalog chooses its first row to contain column names, those names are still string fields passed to the same writer expression. Review mode will apply its prefix to them too. A machine importer that identifies columns by their exact names needs the original contract, not an assumption that the first row escaped the transformation. Decide whether the review representation even needs an importable header before presenting it as a second interchangeable download. The current fixture does not implement schema inference or recognize a row merely because its cells look like familiar field names.

Likewise, the outer iterable and an individual row are different input boundaries. The wrapper loops over the supplied rows, while the explicit list-or-tuple check applies to each row encountered. It does not require every dataset to be stored as one particular outer container. A larger caller can choose how to obtain rows, but it must supply the accepted reusable row representation and string cells at that boundary. Keeping these levels distinct avoids replacing the tested iterator-row rejection with an inaccurate claim that the code rejects every possible iterator anywhere in its inputs.

Reproduce the tests before adapting the export contract

Save csv_exports.py, test_example.py and test_contract.py together in a writable directory. Inspect the final list-and-tuple row guard, the string-cell guard and the review expression before running them. From your copy, python -m unittest discover -s . -p test_example.py -v runs the original eight methods, and the corresponding command with test_contract.py runs the additional six. These are reproduction instructions. The project records the actual interpreter, absolute discovery paths and source hashes used for the local checks.

The recorded environment is Python 3.12.3 on Windows. The tests operate on text in StringIO; the separately retained output step writes UTF-8 files. If you change encoding, dialect, newline behavior or consumer application, document that change and add a check at the relevant boundary. Do not attribute it to the existing tests merely because they still pass on their original inputs. Likewise, accepting generator rows would change the explicit row contract and needs implementation work, rather than deleting the rejection assertion to make a new caller appear supported.

For the immediate project, the outcomes are concrete: the machine serializer preserves the tested strings under the Python CSV reader, the review serializer deliberately prefixes every field, and both source and transformed outputs remain separately identified. The original eight methods were rerun against the final helper, with six more cases defining its boundaries. That supports a useful export component while leaving spreadsheet interpretation, file delivery, UI design and schema enforcement attached to the operations that must actually implement and test them.

test_example.py

from io import StringIO
import csv,unittest
from csv_exports import export_rows
def read(text):return list(csv.reader(StringIO(text,newline='')))
class CsvTests(unittest.TestCase):
 def test_machine_export_preserves_formula_text(self):self.assertEqual(read(export_rows([['=1+2']])) ,[['=1+2']])
 def test_review_adds_apostrophe_to_every_field(self):self.assertEqual(read(export_rows([['=1+2','plain']],True)),[["'=1+2","'plain"]])
 def test_delimiter_and_quote_remain_in_one_cell(self):self.assertEqual(read(export_rows([['a,"b']],True)),[["'a,\"b"]])
 def test_multiline_cell(self):self.assertEqual(read(export_rows([['a\nb']])),[['a\nb']])
 def test_arabic(self):self.assertEqual(read(export_rows([['صورة']])),[['صورة']])
 def test_empty_cell_changes_in_review_contract(self):self.assertEqual(read(export_rows([['']],True)),[["'"]])
 def test_source_unchanged(self):
  rows=[['=1+2']];export_rows(rows,True);self.assertEqual(rows,[['=1+2']])
 def test_nonstring_rejected(self):
  with self.assertRaises(TypeError):export_rows([[1]])

test_contract.py

from io import StringIO
import csv,unittest
from csv_exports import export_rows

def read(text):return list(csv.reader(StringIO(text,newline='')))

class ConsumerContractTests(unittest.TestCase):
    def test_tuple_row_is_accepted(self):
        self.assertEqual(read(export_rows([('a','b')])),[['a','b']])

    def test_string_row_is_rejected(self):
        with self.assertRaises(TypeError):export_rows(['ab'])

    def test_iterator_row_is_rejected(self):
        with self.assertRaises(TypeError):export_rows([iter(['a','b'])])

    def test_empty_row_differs_from_empty_cell(self):
        self.assertEqual(read(export_rows([[]],True)),[[]])
        self.assertEqual(read(export_rows([['']],True)),[["'"]])

    def test_arabic_review_value(self):
        self.assertEqual(read(export_rows([['صورة']],True)),[["'صورة"]])

    def test_multiline_review_value(self):
        self.assertEqual(read(export_rows([['a\nb']],True)),[["'a\nb"]])

Prepared with AI assistance and automated reviews. The original code was run locally within the recorded test scope. The lead image is illustrative; it is not a field photograph or evidence of a browser, spreadsheet or video test.