io
import ioHigh-level path helpers
| Signature | Description |
|---|---|
io.read_text(path: str) -> str | Read entire file as string |
io.write_text(path: str, data: str) -> None | Write string to file (overwrite) |
io.append_text(path: str, data: str) -> None | Append string to file |
io.exists(path: str) -> bool | Check 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.
| Signature | Description |
|---|---|
io.open(path: str, mode: str) -> io.File | Open a file ("r", "w", "a") |
io.read(file: io.File) -> str | Read entire file |
io.read_line(file: io.File) -> str | Read next line (without trailing newline, "" at EOF) |
io.write(file: io.File, data: str) -> None | Write to file |
io.flush(file: io.File) -> None | Flush buffers |
io.close(file: io.File) -> None | Close 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))