Skip to content

io

import io

High-level path helpers

SignatureDescription
io.read_text(path: str) -> strRead entire file as string
io.write_text(path: str, data: str) -> NoneWrite string to file (overwrite)
io.append_text(path: str, data: str) -> NoneAppend string to file
io.exists(path: str) -> boolCheck if path exists

File handle operations

io.File is an opaque managed handle. It is not a normal value type and cannot be stored in unions.

SignatureDescription
io.open(path: str, mode: str) -> io.FileOpen a file ("r", "w", "a")
io.read(file: io.File) -> strRead entire file
io.read_line(file: io.File) -> strRead next line (without trailing newline, "" at EOF)
io.write(file: io.File, data: str) -> NoneWrite to file
io.flush(file: io.File) -> NoneFlush buffers
io.close(file: io.File) -> NoneClose file

Examples

import io
def main() -> None:
path: str = "/tmp/example.txt"
io.write_text(path, "hello")
io.append_text(path, " world")
print(io.exists(path))
print(io.read_text(path))
import io
def main() -> None:
path: str = "/tmp/example.txt"
f: io.File = io.open(path, "w")
io.write(f, "alpha\nbeta\n")
io.flush(f)
io.close(f)
f = io.open(path, "r")
print(io.read_line(f))
print(io.read_line(f))
io.close(f)

with statement

Use with to ensure the file is closed automatically:

import io
def main() -> None:
path: str = "/tmp/example.txt"
writer: io.File = io.open(path, "w")
with writer as file:
io.write(file, "first\n")
io.write(file, "second\n")
io.flush(file)
io.close(writer) # writer is still valid here
with io.open(path, "r") as file:
print(io.read_line(file))
print(io.read_line(file))