fs
The fs module reads and writes files and works with directories. There are seven functions, and none of them stops the program on failure: each one reports it with an empty result or false. This page covers every function, what "failure" looks like for each, and the patterns for reading line-based and JSON files.
import fs
fn main():
path = "/tmp/tern_fs_intro.txt"
fs.write(path, "hello\n")
fs.append(path, "world\n")
print(fs.read(path).split("\n"))
fs.remove(path)["hello", "world", ""]Paths are plain strings, passed to the operating system as they are. A relative path is relative to the directory the program was started in (not the program's own location). Files are read and written as bytes, with no newline translation or encoding checks.
read
fn read(path: str) strThe whole file as a string. If the file can't be read (it doesn't exist, it's a directory, or permission is denied), read returns "". An empty file also gives "", so when the difference matters, check fs.exists(path) first.
The file is read in one go into memory. Strings are limited to 4GB.
import fs
fn main():
print(fs.read("/tmp/no_such_file_here.txt") == "")
fs.write("/tmp/tern_fs_scores.txt", "ada,36\nbob,25\n")
total = 0
for line in fs.read("/tmp/tern_fs_scores.txt").split("\n"):
if line == "":
continue # the text ends with "\n": skip the empty last piece
cols = line.split(",")
total += cols[1].to_int(0)
print(total)
fs.remove("/tmp/tern_fs_scores.txt")true
61text.split("\n") on text that ends with a newline gives an empty last element. Skip empty lines as above, or split text.trim() (which also removes leading whitespace). Files written on Windows have \r\n line ends: line.trim() removes the \r.
write
fn write(path: str, text: str) boolCreates the file, or empties it if it exists, and writes text. Returns true if every byte was written and the file was closed cleanly. Returns false if the file can't be created, for example because its directory doesn't exist (write doesn't create directories; use mkdir) or permission is denied.
The write is not atomic: a crash halfway through can leave a partial file. To replace an important file safely, write a temporary file next to it and check the result before removing the old one.
append
fn append(path: str, text: str) boolAdds text to the end of the file, creating it if it doesn't exist. Returns false in the same cases as write. Each call opens and closes the file, so it's fine for logs but slow for writing a large file piece by piece: build the text in a string and write it once.
import fs
fn main():
log = "/tmp/tern_fs_app.log"
fs.remove(log)
for event in ["start", "load config", "ready"]:
fs.append(log, event + "\n")
print(fs.read(log))
print(fs.write("/tmp/no/such/dir/x.txt", "data"))
fs.remove(log)start
load config
ready
falseexists
fn exists(path: str) booltrue if something exists at path: a file or a directory.
remove
fn remove(path: str) boolDeletes a file, or an empty directory. Returns false if nothing was removed: the path doesn't exist, the directory isn't empty, or permission is denied. There is no recursive delete; list the directory and remove its entries first.
mkdir
fn mkdir(path: str) boolCreates one directory (permissions 755, before the umask). Returns true if the directory was created or already exists, so it is safe to call every time the program starts. The parent must exist: mkdir("a/b/c") fails if a/b doesn't. Note that mkdir also returns true if a file already has that name.
list
fn list(dir: str) [str]The names of the entries in a directory: files and subdirectories, without . and .., and without the directory's path in front. The order is whatever the operating system returns, which is not sorted; sort with sort_by. A missing or unreadable directory gives []. Entries aren't marked as files or directories (list_marked marks them), and list doesn't look inside subdirectories.
import fs
fn main():
dir = "/tmp/tern_fs_demo"
print(fs.mkdir(dir), fs.mkdir(dir))
fs.write(dir + "/b.txt", "2")
fs.write(dir + "/a.txt", "1")
print(fs.list(dir).sort_by(fn(n) n), fs.exists(dir + "/a.txt"))
print(fs.remove(dir)) # not empty yet
for name in fs.list(dir):
fs.remove(dir + "/" + name)
print(fs.remove(dir), fs.exists(dir), fs.list(dir))true true
["a.txt", "b.txt"] true
false
true false []list_marked
fn list_marked(dir: str) [str]list, with a / after the name of each directory (a symlink to one counts). The operating system says which entries are directories while listing them, so this is one system call per batch of names, where list followed by stat of every name is one more per name: walking a tree of 20,000 files takes about a third of the time.
import fs
fn main():
dir = "/tmp/tern_fs_marked"
fs.remove_all(dir)
fs.mkdir(dir)
fs.mkdir(dir + "/sub")
fs.write(dir + "/a.txt", "1")
print(fs.list_marked(dir).sort_by(fn(n) n))
fs.remove_all(dir)["a.txt", "sub/"]error
fn error() strWhy the last fs call on this thread failed, with the operating system's reason: "can't read notes.txt: No such file or directory", "can't write /etc/x: Permission denied". It is "" after a call that succeeded, so check it right after the call you care about.
stat and rename
fn stat(path: str) Info
fn rename(from: str, to: str) boolInfo has the fields exists, is_dir, size (bytes) and modified (seconds since 1970, like time.now()). For a path that can't be read, exists is false and fs.error() says why. rename moves a file or directory (replacing a file at to); within one file system it is atomic, which makes "write to a temporary name, then rename" the safe way to replace a file.
walk, copy, chmod, remove_all, temp_dir
fn walk(dir: str) [str]
fn copy(from: str, to: str) bool
fn chmod(path: str, mode: int) bool
fn remove_all(path: str) bool
fn temp_dir(prefix: str) strchmod sets a file's permission bits: fs.chmod(path, 0o600) lets only its owner read and write it, which is what a file holding a key or a secret wants (on WebAssembly, which has no permissions, it only checks that the file exists).
walk lists every file below dir (not the directories themselves), as dir/sub/name paths, sorted. copy copies a file's bytes and its permissions (a copied program stays runnable). remove_all removes a file, or a directory and everything in it; it returns true if the path is gone, including when it never existed. temp_dir makes a new empty directory in $TMPDIR (or /tmp) whose name starts with prefix.
import fs
fn main():
d = fs.temp_dir("demo")
fs.mkdir(d + "/src")
fs.write(d + "/src/a.tn", "a")
fs.write(d + "/notes.txt", "n")
fs.copy(d + "/notes.txt", d + "/src/b.txt")
for f in fs.walk(d):
print(f[len(d)..])
print(fs.remove_all(d), fs.exists(d))/notes.txt
/src/a.tn
/src/b.txt
true falseReading and writing a piece at a time
fn open(path: str) File for reading
fn create(path: str) File for writing (an existing file is emptied)
fn open_append(path: str) File for writing at the end
fn ok(f: File) bool
fn read_line(f: File) str the next line with its "\n" ("" at the end)
fn read_some(f: File, max: int) str up to max bytes: on a pipe, what has arrived ("" at the end)
fn read_at(f: File, off: int, n: int) str n bytes at offset off, fewer at the end ("" past it);
read_line / read_some's position doesn't move
fn put(f: File, text: str) bool buffered: see flush
fn flush(f: File) bool write out what was put so far (readers see it now)
fn close(f: File) boolFor files too big to read at once, or logs written as you go. Check f.ok() after opening (fs.error() says why it failed). Lines keep their "\n", so an empty line is "\n" and only the end of the file is ""; the last line may lack the "\n". Writes are buffered: f.flush() writes out what was put so far, and f.close() (or the program's end) writes out the rest. Reading at the end of a file that is still growing (a log) returns "", and the next read picks up what was added since.
import fs
fn main():
path = "/tmp/tern_fs_doc.txt"
out = fs.create(path)
for i in 0..3:
out.put(f"line {i}\n")
out.close()
f = fs.open(path)
n = 0
line = f.read_line()
while line != "":
n += 1
line = f.read_line()
f.close()
info = fs.stat(path)
print(n, info.size, info.is_dir)
print(fs.rename(path, path + ".old"), fs.exists(path))
fs.remove(path + ".old")
print(fs.open(path).ok(), fs.error())3 21 false
true false
false can't open /tmp/tern_fs_doc.txt: No such file or directoryIn a task, file calls run on the task's thread; for very large files use task.blocking so the other tasks on that core keep running.
With Result
fn try_read(path: str) Result[str, str]
fn try_write(path: str, text: str) Result[int, str] bytes written
fn try_append(path: str, text: str) Result[int, str]
fn try_list(dir: str) Result[[str], str]
fn try_stat(path: str) Result[Info, str]
fn try_open(path: str) Result[File, str]The same operations as Result values, whose error says what failed and why, so ? can pass a failure up:
import fs
fn port_from(path: str) Result[int, str]:
text = fs.try_read(path)?
port = text.trim().to_int(-1)
if port < 0:
return Err("config: not a port number: " + text.trim())
return Ok(port)
fn main():
fs.try_write("/tmp/tern_port.txt", "8080\n")
print(port_from("/tmp/tern_port.txt").unwrap_or(80))
r = port_from("/tmp/tern_no_such_file")
if r is Err(e):
print(e)8080
fs: can't read /tmp/tern_no_such_file: No such file or directoryA complete example
A small note-taking store: settings in a JSON file with defaults, and one file per note in a directory:
import fs
import json
struct Settings:
author: str
max_notes: int
fn load_settings(path: str) Settings:
s = Settings("anonymous", 100) # defaults
if fs.exists(path):
if not json.decode(fs.read(path), &s):
print("warning: bad settings file, using defaults")
return s
fn save_note(dir: str, title: str, body: str) bool:
if not fs.mkdir(dir):
return false
name = title.lower().replace(" ", "-") + ".txt"
return fs.write(dir + "/" + name, body + "\n")
fn main():
root = "/tmp/tern_notes"
fs.write(root + ".json", `{"author": "ada"}`)
s = load_settings(root + ".json")
print(s.author, s.max_notes)
save_note(root, "Shopping List", "tea, milk")
save_note(root, "Ideas", "a compiler with no references")
for name in fs.list(root).sort_by(fn(n) n):
print(name + ": " + fs.read(root + "/" + name).trim())
for name in fs.list(root):
fs.remove(root + "/" + name)
fs.remove(root)
fs.remove(root + ".json")ada 100
ideas.txt: a compiler with no references
shopping-list.txt: tea, milk