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.
Writing and reading a file
Section titled “Writing and reading a file”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 listeggs: 12milk: 2Step by step:
open("notes.txt", "w")opens the file for writing, creating it if needed. Thewithblock closes it when the block ends (the Mojo Context Managers lesson explains how).f.write(...)takes any number of values, likeprint, but adds no spaces and no newline. You write the\nyourself.open("notes.txt", "r")opens it for reading, andf.read()returns the whole file as oneString.remove()fromstd.osdeletes the file.
main is marked raises because opening a file can fail, and so can reading or writing. More on that below.
Reading line by line
Section titled “Reading line by line”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 moduleInstead, 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 lines1: Roses are red2: Violets are blue3:4: Mojo is fastsplitlines() 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!.
Appending and the other modes
Section titled “Appending and the other modes”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: okday 2: okday 3: okfresh startWhen the file isn’t there
Section titled “When the file isn’t there”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 directoryThe 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.
Paths with pathlib
Section titled “Paths with pathlib”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 Pathfrom 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 Falsereport.txt .txtTotal: 3 itemsFalsewrite_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.
Working with folders
Section titled “Working with folders”To build paths, join them with /, just like Python. The folder functions live in std.os:
from std.pathlib import Pathfrom std.os import makedirs, remove, rmdirfrom 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.csvnotes.txt 12 bytesscores.csv 16 bytesFalsemakedirs(path, exist_ok=True)creates a folder and any missing parents, and doesn’t complain if it already exists.mkdircreates just one level.listdir()gives the names inside the folder (notes.txt, notdata/notes.txt), in no particular order, so we sort them. Join them back withfolder / item.getsize()fromstd.os.pathreturns a file’s size in bytes. That module also hasexists,isfile,isdir,join,basenameand more, for when you’d rather work with plain strings.rmdironly removes an empty folder, so the files go first.
A small report from a CSV file
Section titled “A small report from a CSV file”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: 90Linus: 85Grace: 97average: 90.66666666666667The 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.
Practice
Section titled “Practice”1. Count lines and words
Section titled “1. Count lines and words”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 Pathfrom 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: 3words: 12bytes: 64The 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.
2. Save and load scores
Section titled “2. Save and load scores”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 Pathfrom 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: 210f.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 awithblock so the file is closed for you.f.write(...)adds no newline;f.read()returns the whole file as aString.- 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. Pathfromstd.pathlibhasread_text,write_text,exists,name(),suffix(),listdir()and/for joining; folder tools likemakedirs,removeandrmdirare instd.os.
Next up: Mojo environment variables, reading settings from the world outside your program.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”openreference: the function and the modes it accepts.FileHandlereference: every method on an open file, includingread,read_bytes,seekandwrite.Pathreference: thepathlibtype and its methods.ospackage: folders, file removal and theos.pathhelpers.- Python’s reading and writing files tutorial: the Python way, for comparison.