std/io module. This example demonstrates reading and writing files using both convenience functions and handle-based operations.
Basic file operations
The simplest way to work with files is using the convenience functions:How to run
Save the code to a file calledfile_io.walrus and run it:
Expected output
Handle-based operations
For more control, especially with larger files or streaming operations, use file handles:Output
File existence check
You can check if a file exists before reading:Complete example
Here’s a complete example that demonstrates all file operations:Output
Available functions
| Function | Description |
|---|---|
io.file_open(path, mode) | Open a file, returns a handle. Modes: "r", "w", "a", "rw" |
io.file_read(handle) | Read entire file contents as string |
io.file_read_line(handle) | Read a single line (returns void at EOF) |
io.file_write(handle, content) | Write string to file, returns bytes written |
io.file_close(handle) | Close a file handle |
io.file_exists(path) | Check if a file exists (returns bool) |
io.read_file(path) | Convenience: read entire file in one call |
io.write_file(path, content) | Convenience: write entire file in one call |
Key concepts
- Import statement: Use
import "std/io"to access file I/O functions - File modes:
"r"for reading,"w"for writing,"a"for appending,"rw"for read-write - Void type:
file_read_linereturnsvoidwhen reaching end of file - Handle management: Always close file handles when done