Skip to content

Mojo File I/O

Most real programs save something: settings, results, a log, a report. In Mojo you work with files through open(), which is always available, and the Path type from std.pathlib. If you’ve done file work in Python, you’ll recognise nearly all of it, but there are a few gaps and one surprise, all pointed out below.

Every program on this page writes its files in the current folder, reads them back, and deletes them at the end, so you can run each one as is. Checked with Mojo 1.2 on Linux.

from std.os import remove
def main() raises:
with open("notes.txt", "w") as f:
f.write("Shopping list\n")
f.write("eggs: ", 12, "\n")
f.write("milk: ", 2, "\n")
with open("notes.txt", "r") as f:
var text = f.read()
print(text, end="")
remove("notes.txt")

Output:

Shopping list
eggs: 12
milk: 2

Step by step:

  • open("notes.txt", "w") opens the file for writing, creating it if needed. The with block closes it when the block ends (the Mojo Context Managers lesson explains how).
  • f.write(...) takes any number of values, like print, but adds no spaces and no newline. You write the \n yourself.
  • open("notes.txt", "r") opens it for reading, and f.read() returns the whole file as one String.
  • remove() from std.os deletes the file.

main is marked raises because opening a file can fail, and so can reading or writing. More on that below.

In Python you’d write for line in f:. In Mojo 1.2 a file handle can’t be looped over:

def main() raises:
var f = open("poem.txt", "w")
for line in f:
print(line)
poem.mojo:3:17: error: 'FileHandle' does not implement the '__iter__' method
for line in f:
^
mojo: error: failed to parse the provided Mojo source module

Instead, read the whole file and split it with .splitlines():

from std.os import remove
def main() raises:
with open("poem.txt", "w") as f:
f.write("Roses are red\nViolets are blue\n\nMojo is fast\n")
var text = open("poem.txt", "r").read()
var lines = text.splitlines()
print(len(lines), "lines")
for i in range(len(lines)):
print(t"{i + 1}: {lines[i]}")
remove("poem.txt")

Output:

4 lines
1: Roses are red
2: Violets are blue
3:
4: Mojo is fast

splitlines() drops the newline characters and keeps empty lines (line 3). Reading everything at once is fine for most text files. For very large ones, f.read(n) reads at most n bytes at a time: after f.read(5) on a file containing Hello, world! you get Hello, and the next f.read() continues with , world!.

The second argument to open() is the mode. Mojo 1.2 knows four:

Mode Meaning If the file exists If it doesn’t
"r" read reads it error
"w" write empties it first creates it
"a" append adds to the end creates it
"rw" read and write keeps it creates it

Anything else, such as Python’s "x" or "rb", raises invalid mode: "x". Can only be one of: {"r", "w", "rw", "a"}. Here’s "a" building up a log, then "w" wiping it:

from std.os import remove
def main() raises:
for day in range(1, 4):
with open("log.txt", "a") as f:
f.write("day ", day, ": ok\n")
print(open("log.txt", "r").read(), end="")
with open("log.txt", "w") as f:
f.write("fresh start\n")
print(open("log.txt", "r").read(), end="")
remove("log.txt")

Output:

day 1: ok
day 2: ok
day 3: ok
fresh start

Opening a missing file for reading raises an error. Catch it to give a clear message:

def main():
try:
var text = open("missing.txt", "r").read()
print(text)
except e:
print("Couldn't read the file:", e)

Output:

Couldn't read the file: Failed to open file 'missing.txt': No such file or directory

The message includes the file name and the reason from the operating system. A missing file is the most common reason, but you’d see a different one for, say, a file you don’t have permission to read.

Writing has a surprise in the other direction: in our tests, open("out/report.txt", "w") created the missing out folder and wrote the file. Python would raise FileNotFoundError there. The open reference doesn’t mention this, so don’t depend on it: create folders yourself, as shown below.

Path from std.pathlib represents a file or folder name, with handy methods. It works much like Python’s pathlib.Path:

from std.pathlib import Path
from std.os import remove
def main() raises:
var p = Path("report.txt")
p.write_text("Total: 3 items\n")
print(p.exists(), p.is_file(), p.is_dir())
print(p.name(), p.suffix())
print(p.read_text(), end="")
remove(p)
print(p.exists())

Output:

True True False
report.txt .txt
Total: 3 items
False

write_text() and read_text() do a whole open-write-close or open-read-close in one call, which is perfect for small files. name() and suffix() are methods in Mojo (with brackets), where Python uses properties. Anywhere a file name is expected, such as open() or remove(), a Path works as well as a string.

To build paths, join them with /, just like Python. The folder functions live in std.os:

from std.pathlib import Path
from std.os import makedirs, remove, rmdir
from std.os.path import getsize
def main() raises:
var folder = Path("data")
makedirs(folder, exist_ok=True)
var scores = folder / "scores.csv"
print(scores)
scores.write_text("ada,90\nlinus,85\n")
(folder / "notes.txt").write_text("check linus\n")
var items = folder.listdir()
sort(items)
for item in items:
print(item, getsize(folder / item), "bytes")
remove(scores)
remove(folder / "notes.txt")
rmdir(folder)
print(folder.exists())

Output:

data/scores.csv
notes.txt 12 bytes
scores.csv 16 bytes
False
  • makedirs(path, exist_ok=True) creates a folder and any missing parents, and doesn’t complain if it already exists. mkdir creates just one level.
  • listdir() gives the names inside the folder (notes.txt, not data/notes.txt), in no particular order, so we sort them. Join them back with folder / item.
  • getsize() from std.os.path returns a file’s size in bytes. That module also has exists, isfile, isdir, join, basename and more, for when you’d rather work with plain strings.
  • rmdir only removes an empty folder, so the files go first.

Putting it together: write a CSV file, then read it back, split each line at the commas and add up a column:

from std.os import remove
def main() raises:
with open("scores.csv", "w") as f:
f.write("name,score\n")
f.write("Ada,90\n")
f.write("Linus,85\n")
f.write("Grace,97\n")
var text = open("scores.csv", "r").read()
var lines = text.splitlines()
var total = 0
for i in range(1, len(lines)):
var fields = lines[i].split(",")
var score = Int(fields[1])
total += score
print(t"{fields[0]}: {score}")
print("average:", Float64(total) / Float64(len(lines) - 1))
remove("scores.csv")

Output:

Ada: 90
Linus: 85
Grace: 97
average: 90.66666666666667

The loop starts at 1 to skip the header line. split(",") cuts a line into fields, and Int() turns the score text into a number (it raises on bad data, which main passes on). This simple split is fine for your own files; real-world CSV with quoted commas needs a proper parser.

Write a short story to story.txt with Path.write_text, then read it back and print the number of lines, words and bytes. Delete the file at the end.

Hint: line.split() with no argument splits on any run of spaces. text.byte_length() gives the size in bytes.

Show solution
from std.pathlib import Path
from std.os import remove
def main() raises:
var p = Path("story.txt")
p.write_text("Once upon a time\nthere was a small program\nthat counted words.\n")
var text = p.read_text()
var lines = text.splitlines()
var words = 0
for line in lines:
words += len(line.split())
print("lines:", len(lines))
print("words:", words)
print("bytes:", text.byte_length())
remove(p)

Output:

lines: 3
words: 12
bytes: 64

The double space in the second line doesn’t create an empty word, because split() without an argument treats any run of spaces as one separator.

Write two functions: save_scores(path, scores) writes a List[Int] to a file, one number per line, and load_scores(path) reads them back into a new list. Use them in main and print the best score.

Hint: a function that returns a local List needs return result^.

Show solution
from std.pathlib import Path
from std.os import remove
def save_scores(path: Path, scores: List[Int]) raises:
with open(path, "w") as f:
for s in scores:
f.write(s, "\n")
def load_scores(path: Path) raises -> List[Int]:
var result: List[Int] = []
for line in path.read_text().splitlines():
result.append(Int(line))
return result^
def main() raises:
var path = Path("scores.txt")
var scores: List[Int] = [120, 95, 210]
save_scores(path, scores)
var loaded = load_scores(path)
print(loaded)
var best = loaded[0]
for s in loaded:
if s > best:
best = s
print("best:", best)
remove(path)

Output:

[120, 95, 210]
best: 210

f.write(s, "\n") writes each number as text. Reading turns each line back into an Int. Both functions are raises, because both can hit file errors.

  • open(path, mode) with "r", "w", "a" or "rw"; use it in a with block so the file is closed for you.
  • f.write(...) adds no newline; f.read() returns the whole file as a String.
  • A file handle can’t be looped over: use f.read().splitlines().
  • "w" empties an existing file; "a" appends.
  • Opening a missing file for reading raises; catch it with try / except.
  • Path from std.pathlib has read_text, write_text, exists, name(), suffix(), listdir() and / for joining; folder tools like makedirs, remove and rmdir are in std.os.

Next up: Mojo environment variables, reading settings from the world outside your program.

Quick check

1. You open an existing log.txt with open("log.txt", "w"). What happens to its old content?
2. How do you go through a file line by line in Mojo 1.2?
3. What does f.write("total: ", 5) write?
4. Which line builds the path data/scores.csv from a Path called folder?