fs
The fs module provides file system operations: reading, writing, and managing files and directories.
Module functions
fs.read(path)
Reads the entire contents of a file and returns it as a string.
fs.write(path, content)
Writes a string to a file, creating it if it does not exist and overwriting it if it does.
fs.open(path, mode)
Opens a file and returns a file object. The mode must be one of:
| Mode | Description |
|---|---|
"r" |
Read |
"w" |
Write (create/overwrite) |
"a" |
Append |
See File objects below for the methods available on file objects.
fs.exists(path)
Returns true if the file or directory exists, false otherwise.
fs.remove(path)
Deletes a file. Throws an error if the file does not exist.
fs.mkdir(path)
Creates a directory. Pass true as the second argument to create parent directories and ignore existing ones:
File objects
File objects are returned by fs.open(). They have these methods:
| Method | Description |
|---|---|
.read() |
Read all remaining content as a string |
.readline() |
Read the next line (without newline) |
.readlines() |
Read all lines as a list of strings |
.write(str) |
Write a string to the file |
.close() |
Close the file |
Reading line by line
import fs
import console
function main() {
var File f = fs.open("data.txt", "r")
var list lines = f.readlines()
f.close()
for line in lines {
console.println(line)
}
}
Using with for automatic cleanup
The with statement calls .close() automatically when the block exits:
import fs
import console
function main() {
with fs.open("data.txt", "r") as f {
var string content = f.read()
console.println(content)
}
}
Full example
import console
import fs
function main() {
// write a file
fs.write("greeting.txt", "Hello from CColon!")
// read it back
var string content = fs.read("greeting.txt")
console.println(content)
// append to it
with fs.open("greeting.txt", "a") as f {
f.write("\nGoodbye!")
}
// read updated content
console.println(fs.read("greeting.txt"))
// clean up
fs.remove("greeting.txt")
}