Read and write a whole file
Read a file into one string, change it, and write it back.
- Read the file with File.read. It returns the whole file as a string.
- Change the text, here with String.replace.
- Write it with File.write. It creates the file, or replaces what the file held.
- Use
tryon both calls, so a script stops at a missing file or a failed write, writes the error to standard error, and exits with status 1.
let text = try File.read("todo.txt")
try File.write("todo.txt", text.replace("[ ] call Ann", "[x] call Ann"))
print(try File.read("todo.txt"))[ ] buy milk
[x] call AnnFor a file too large to hold in memory, read it a line at a time instead: Read a large file line by line.
Write a new file without replacing one
Pass replace: false to create the file only when nothing is at the path. When something is, the write is an Err and the file keeps what it held:
println(File.write("report.txt", "second report", replace: false))
print(try File.read("report.txt"))Err{ error: Error{ message: "open report.txt: file exists" } }
first reportSay what the program was doing
In a function that returns a Result, use try to return the Err to the caller, and Result.wrapErr to say what the function was doing. The error already names the file:
func countWords(path: string): Result[int, Error] {
let text = try (File.read(path) | Result.wrapErr("count words"))
Result.ok(text.fields().length())
}
try File.write("poem.txt", "so much depends\nupon a red wheel\nbarrow\n")
println(countWords("poem.txt"))
println(countWords("missing.txt"))Ok{ value: 8 }
Err{ error: Error{ message: "count words: open missing.txt: no such file or directory" } }String.fields splits the text at runs of white space.
Create the directory first
File.write does not create missing directories. Create them with File.mkdir, which makes the missing parents too and is Ok when the directory already exists, and build the path with Path.join:
let dir = Path.join(["out", "2026"])
let path = Path.join([dir, "summary.txt"])
println(File.write(path, "done\n"))
try File.mkdir(dir)
try File.write(path, "done\n")
print(try File.read(path))Err{ error: Error{ message: "open out/2026/summary.txt: no such file or directory" } }
doneAdd to the end of a file
File.write replaces what the file held. To add to it, open it with File.append, which creates the file when it is missing, and close it with defer:
try File.write("log.txt", "started\n")
let log = try File.append("log.txt")
defer { log.close() }
try log.writeLine("finished")
print(try File.read("log.txt"))started
finishedRead and write bytes
For a file that is not text, such as an image, use File.readBytes and File.writeBytes. They keep the bytes as they are. This program writes the first bytes of a PNG file and checks for them with Bytes.startsWith:
let signature = Bytes.fromArray([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
try File.writeBytes("logo.png", signature)
let data = try File.readBytes("logo.png")
println(data.length())
println(data.startsWith(signature))8
trueBytes.fromArray makes the bytes from numbers.
Check that a file is text
File.read replaces bytes that are not valid UTF-8 with U+FFFD, �, so the read never fails on such a file. To find out whether a file is text, read its bytes and convert them with String.fromBytes, which returns null for bytes that are not UTF-8:
try File.writeBytes("name.txt", Bytes.fromArray([0x41, 0x6e, 0xff]))
println(try File.read("name.txt"))
if String.fromBytes(try File.readBytes("name.txt")) == null {
println("name.txt is not UTF-8")
}An�
name.txt is not UTF-8See also
File.read · File.write · File.readBytes · File.writeBytes · File.append · File.mkdir · Path.join · Result.wrapErr · String.replace · String.fields · String.fromBytes · Bytes.fromArray · Bytes.startsWith · Read a large file line by line · Replace a file without a partial write
