Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Write through a file

Use a writable stream when several writes belong to one open file. write(text) returns the number of Unicode characters written and preserves exact UTF-8 bytes, including newlines. Mode "w" replaces a file; "a" appends to it.

Run this in a scratch directory: it replaces plenty-stream.txt.

def main() -> Result[(), IoError]:
    with open("plenty-stream.txt", "w")? as file:
        print(file.write("hello\n")?)?
        file.write("world\n")?
        file.close()?
    with open("plenty-stream.txt", "a")? as file:
        file.write("goodbye\n")?
    print(read_text("plenty-stream.txt")?)?
    Ok(())
6
hello
world
goodbye

Call close()? to report a close error; automatic cleanup cannot report it. Exiting the block can then close the already closed file harmlessly.

For flushing, disk synchronization, and other detailed contracts, see the text I/O reference.