What this is about
A CSV file is a plain text table. Each line is a row. Commas separate the columns. Spreadsheet programs can save and open it, and so can almost every tool in the world.
This article shows how to read a CSV file in Mojo, how to write one back, and the one rule that surprises beginners: a row you read is only borrowed until you ask for the next row.
Why it matters
CSV is the lowest common language of data. Bank exports, sensor logs and school grade sheets all use it. If you can read and write it, you can move data between almost any two programs.
It looks simple, but it has traps. A name such as smith, bo has a comma inside it. A file may use quotes to protect it. A program that just splits on commas will break that row. A good CSV reader knows all these rules.
How it works
Take this tiny file:
name,score
ada,9
"smith, bo",7
Every row has two columns, even though the last line has two commas. The quotes protect the comma in the name.
Here is a Mojo program that reads the rows and writes them back. We ran it on Mojo 1.2.0 with our mojo-csv library.
from csv import Reader, Dialect, write_all, OwnedField
def main() raises:
var input = List[UInt8]()
for c in "name,score\nada,9\n\"smith, bo\",7\n".as_bytes():
input.append(c)
var reader = Reader(Dialect.excel(), Span(input))
var saved = List[List[OwnedField]]()
while reader.next():
var row = reader.row()
print("fields", len(row))
saved.append(row.to_list())
var output = write_all(saved, Dialect.excel())
print("rows", len(saved), "written bytes", len(output), "input bytes", len(input))
It printed fields 2 three times and then rows 3 written bytes 34 input bytes 31.
Walk through it:
- Put the bytes in a list. The reader works on bytes. We typed the text in. In a real program you would fill the list from a file's bytes.
- Make a reader.
Dialect.excel()means "comma separated, quotes protect commas", the common spreadsheet style. - Loop with
next(). Each call moves to the following row.reader.row()gives you a view of the current row. - Copy what you keep.
row.to_list()makes an owned copy. This is the key rule, and we explain it below. - Write back.
write_all(saved, Dialect.excel())makes the bytes of a new CSV file.
Why 34 bytes out and 31 in
The writer ends each line with a carriage return and a line feed, the pair of characters a spreadsheet usually writes. Our input used only a line feed. Three rows gain one extra character each, so 31 becomes 34. We ran the same idea through Python's csv module and it also gave 34. That is the parity check in action.
The one rule: copy before you move on
The reader does not copy each field for you. That is part of why it is fast. For an unquoted field, it points into your input. So the row view is only valid until the next call to next() or reset().
If you want to keep a row, call to_list() before you move on. If you forget, the compiler will not warn you. The README says so plainly: the compiler accepts invalid retention, and the rule is yours to follow. Also, the input must stay alive and unchanged while any view of it is in use.
How fast is it
The README measured 50 MB of mixed records. The reader streamed at 227.50 MB per second against 85.79 for CPython's csv, and write_all ran at 468.2 MB per second against 97.1. Those were measured on one machine, a Ryzen 7 7800X3D, with receipts in the repository. Your files and your machine will give other numbers.
What it does not do
- Controls such as the separator are single bytes, and the field limit is 131,072 bytes.
- It has no
DictReaderorDictWriter, and no Python file-object API. - Error messages are the library's own, not Python's.
The library has moved. It now lives in the mojo-libs repository under libs/csv, and the old mojo-csv repository is read-only.
Why you should not split on commas yourself
It is tempting to read a CSV line and cut it at each comma. On our example, that goes wrong at once. The last line is "smith, bo",7. Cut at every comma and you get three pieces: "smith, bo" and 7. The name is torn in half, and the quotes are stuck to the pieces.
A CSV reader keeps the quote rules. It knows that a comma inside quotes belongs to the field, that two quote marks in a row mean one literal quote mark, and that a field may even contain a line break. Those rules are why the reader above found two fields in every row.
The same check in Python
If you know Python, here is the same test with its csv module:
import csv, io
s = "name,score\nada,9\n\"smith, bo\",7\n"
rows = list(csv.reader(io.StringIO(s)))
print([len(r) for r in rows], len(rows))
It prints [2, 2, 2] 3: three rows, two fields each. That matches what the Mojo program found. This is the idea behind the "parity" in the library's README. Python's csv is the oracle, and the Mojo reader must agree.
Words you may not know
- CSV: comma separated values, a table in plain text.
- Dialect: a set of rules for how a file separates and quotes fields.
- View: a window into data that belongs to something else.
- Owned copy: data you hold yourself, which stays valid when the source changes.
- Carriage return: an old typewriter term, the character that sends the cursor to the line start.
Try it
- Install the library with
pixi add mojo-csv, as in the mojo-libs install steps. - Read the mojo-csv repository README and its
docs/api.md. - Save a small table from a spreadsheet as CSV and run it through the program above.
- Compare your result with Python's
csv.readeron the same file.
Read next
- Oracle tests: checking new code against code you trust shows how to prove two programs read a file the same way.

Comentarii
Niciun comentariu încă.
Conectare pentru a comenta.