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

The io module

Files, directories, paths, and sockets, modeled on Rust’s std::fs, std::path and std::net.

Unlike the rest of the standard library, io is a module: bring it in with import io (and write io.File, io.Path) or import names directly with import [File, Path] from io. Every fallible operation returns an IoResult<T>, a Result whose error is an IoError.

  • Path: building, splitting, and inspecting paths
  • File: opening, reading, writing, and locking files, whole-file helpers, and FileTransfer
  • Directory: listing, creating, and removing directories
  • Network addresses: IpAddress, SocketAddress, and resolve
  • Sockets: TcpListener, Incoming, SharedTcpListener, TcpStream, SocketTransfer, and UdpSocket
  • Unix domain sockets: UnixListener, SharedUnixListener, UnixStream, and UnixDatagram
  • Streams: the Reader and Writer traits, lines() and chunks()
  • Streams in memory: ByteReader and ByteWriter
  • Print: deprecated; use Writer
  • Errors and platform types: IoError, ErrorKind, IoResult, and handle types

Example

import io;

main(): int {
    var path = io.Directory.temp().join("greeting.txt");
    assert(io.File.write_text(path, "hello").is_ok(), "write");
    assert(io.File.read_to_string(path).value() == "hello", "read back");
    io.File.remove(path);
    return 0;
}

Source: runtime/io/module.pep