3.1.25 filesystem
The filesystem library provides functions for reading and writing files, as well as working with paths.
These are selections from Alan Perlis’s Epigrams on Programming
/ ├── hello.txt "Hello, world!" ├── data/ │ ├── words "apple\nbanana\ncherry" │ ├── numbers.txt "1\n2\n3\n4\n5" │ └── story.txt "A long time ago in a galaxy far, far away..."
- read-file-string :: (
- path :: String
- )
import filesystem as FS check: FS.read-file-string("hello.txt") is "Hello, world!" words = FS.read-file-string("data/words") string-split-all(words, "\n") is [list: "apple", "banana", "cherry"] FS.read-file-string("does-not-exist") raises "No such file or directory" end
Reads the file at the given path and returns its contents as a String. Always assumes UTF-8 encoding.
Reports an error if the file is not found or is not readable.
- write-file-string :: (
- path :: String,
- contents :: String
- )
Writes the given contents the file at the given path. Always assumes UTF-8 encoding. If the file exists, it is overwritten, and if it does not exist, it is created.
Reports an error if the path refers to a non-existent directory, or if the file is present but not writable.
import filesystem as FS check: FS.read-file-string("goodbye.txt") raises "No such file or directory" FS.write-file-string("goodbye.txt", "Until next time!") FS.read-file-string("goodbye.txt") is "Until next time!" FS.write-file-string("goodbye.txt", "See ya!") FS.read-file-string("goodbye.txt") is "See ya!" end
There is also an optional field called native that may have additional information sometimes, depending on the platform. The three fields listed are guaranteed to be present across all platforms.
import filesystem as FS check: test-start-time = time-now() # gives the current time in milliseconds FS.write-file-string("fresh-file.txt", "Brand new!") stats = FS.stat("fresh-file.txt") spy: stats end stats.size is string-length("Brand new!") # these tests are just indicating that the file was created and modified after # the test started stats.mtime is%(_ >= _) test-start-time stats.ctime is%(_ >= _) test-start-time end