Files

file(path) makes a file value. With it, a program can save data and read it back:

notes: file = file("notes.txt")
notes.write("Buy milk\n")
notes.add("Call Ann")
print(notes.read())

Output:

Buy milk
Call Ann

A file is just the path: making one doesn’t open or create anything. Each method opens the file, does its work and closes it again.

MethodWhat it does
f.read()gives the contents, as a str, a [str] (the lines), a [byte] or a buffer
f.write(x)replaces the contents with x: a str, a [str], a [byte] or a buffer; creates the file if needed
f.add(line)adds a line (and a new line character) at the end; creates the file if needed
f.exists()true if the file is there
f.delete()deletes the file
f.size()the size in bytes, as an int
f.open()gives a handle, to read and write at any place in the file
f.name(), f.ext(), f.folder()the parts of its path
f.copy(to), f.move(to)copies or moves the file
f.modified(), f.mode()when it last changed, and its permission bits

Paths

A path is relative to the folder the program runs in, unless it starts at the root (/home/ann/notes.txt, C:/Users/Ann/notes.txt). Folders are separated by /, which works on Windows too. Writing a file doesn’t create its folder: writing data/notes.txt needs the folder data to be there, which folder("data").make() makes. To find files next to the code rather than where the program runs, see file.this().

Folders

folder(path) makes a folder value, as file(path) makes a file: just the path, until a method is used.

reports: folder = folder("reports/2024")
reports.make()
reports.file("january.csv").write("day,sales\n")
reports.file("february.csv").write("day,sales\n")
print(reports.files())
print(folder("reports").folders())
reports.files().walk(f) {
    print("${f.name()}: ${f.size()} bytes")
}

Output:

[file("reports/2024/february.csv"), file("reports/2024/january.csv")]
[folder("reports/2024")]
february.csv: 10 bytes
january.csv: 10 bytes
MethodWhat it does
d.make()makes the folder, and the folders above it that aren’t there; nothing if it is there already
d.exists()true if it is there and is a folder
d.delete()deletes the folder, which must be empty
d.clear()deletes all in it, all the way down, and keeps the folder: see Emptying a folder
d.files()the files in it, as a [file], sorted by name
d.folders()the folders in it, as a [folder], sorted by name
d.find(pattern)the files in it, and in the folders inside it, that match a pattern: see Finding files by pattern
d.file(name)the file of that name in it: folder("data").file("notes.txt") is file("data/notes.txt")
d.folder(name)the folder of that name in it; d.folder() without a name is the folder it is in
d.name()its last part: "2024" for folder("reports/2024")
d.move(to)moves the folder, with all in it
  • files() and folders() look only in the folder itself, not in the folders inside it. Names are sorted by their characters (by code point, so Z before a); names that start with . are listed too.
  • A link is listed as what it points to: a file or a folder. One that points nowhere is a file.
  • delete() deletes only an empty folder: clear() it first. It never deletes a file: for a file it raises error 9.
  • Errors are a file’s: a folder that isn’t there is error 8 (folder not found: reports), anything else error 9 (cannot delete folder reports: it is not empty, cannot make folder data: a file of that name is in the way).

Copying and moving

report: file = file("report.csv")
report.write("day,sales\n")
folder("backup").make()
report.copy(file("backup/report-2024.csv"))
report.move(folder("backup"))
print(folder("backup").files())
print(report.exists())

Output:

[file("backup/report-2024.csv"), file("backup/report.csv")]
false
MethodWhat it does
f.copy(to)copies the file: to a file (its new path), or into a folder, with the same name
f.move(to)moves or renames it, the same way
d.move(to)moves or renames a folder, with all in it: to is its new path
d.copy(to)copies a folder, with all in it, all the way down: to is the new folder’s path
  • A file that is there already is replaced, as write replaces what a file had. A folder is never replaced: moving a folder where something of that name is, is error 9.
  • The folder it goes to must be there (error 9 if not): make it first with make().
  • A copy keeps the file’s permission bits (a script stays runnable), not its times. It is made beside the target and takes its place when it is whole, so a program that stops on the way never leaves half a file. Big files are copied in parts, not read into memory at once.
  • Moving is a rename, which is instant. To another disk, it is a copy, and then the original is deleted.
  • A folder’s copy is made beside its new path and takes that path when it is whole: one that stops on the way (a file it may not read) leaves nothing. Files keep their permission bits, folders too.
  • Links are copied as what they point to; one that points nowhere is left out. A link that loops (a folder that links to the folder it is in) stops the copy with error 9, too deep (a link that loops?).
  • Copying a file onto itself is error 9; moving it onto itself does nothing.

Finding files by pattern

d.find(pattern) gives the files in a folder whose paths match a pattern, as a [file] sorted by path:

folder("logs/2024-01").make()
folder("logs/2024-02").make()
file("logs/2024-01/app.log").write("")
file("logs/2024-02/app.log").write("")
file("logs/2024-02/errors.txt").write("")
file("logs/notes.txt").write("")
logs: folder = folder("logs")
print(logs.find("*.txt"))
print(logs.find("**/*.txt"))
print(logs.find("2024-0[2-9]/*"))

Output:

[file("logs/notes.txt")]
[file("logs/2024-02/errors.txt"), file("logs/notes.txt")]
[file("logs/2024-02/app.log"), file("logs/2024-02/errors.txt")]
In a patternMatches
*any characters in one name, also none: *.csv, report-*
?exactly one character
[abc], [a-z], [!0-9]one character of the set, or (with !) one not in it
**any number of folders, also none: **/*.csv is every .csv at any depth
/separates folders, as in paths
anything elseitself
  • A name that starts with . matches only when that part of the pattern starts with . too, and ** doesn’t go into folders such as .git: .* or .git/* finds them.
  • Upper and lower case are different, on every system: *.jpg doesn’t find PHOTO.JPG; *.[jJ][pP][gG] finds both.
  • ** doesn’t follow links to folders, so nothing is found twice and a link that loops can’t trap it; a link that a pattern names (lib/*, when lib is a link) is followed. A link to a file is found as a file.
  • Only files are found; folders() gives the folders. A folder that can’t be read is passed over.
  • A [ without its ] is just a [. To find a name with [ in it, write [[]: x[[]1].txt finds x[1].txt.
  • The same patterns work on any text: s.matches(pattern).

Emptying a folder

d.clear() deletes all in a folder, all the way down, and keeps the folder itself. To delete the folder too, delete() it after:

build: folder = folder("build")
build.folder("pages").make()
build.file("index.html").write("<h1>Hi</h1>")
build.file("pages/about.html").write("<h1>About</h1>")
build.clear()
print(build.files())
print(build.folders())
build.delete()
print(build.exists())

Output:

[]
[]
false
  • A link in the folder is deleted, never what it points to: a link to your home folder inside build doesn’t empty your home folder.
  • The root of a disk (/, C:/) can’t be cleared: error 9.
  • It stops at the first thing it can’t delete (error 9 says which). What it deleted before stays deleted: there is no undo.

Times and permissions

f: file = file("run.sh")
f.write("echo hi\n")
f.mode("755")
print(f.mode())
f.modified(datetime(2024, 12, 25, 9, 30))
print(f.modified())

Output:

755
2024-12-25 09:30:00
MethodWhat it does
f.modified()when the file last changed, a datetime on the local clock (to the millisecond, where the system keeps it)
f.modified(when)sets it (as touch does; when it was last read stays)
f.mode()its permission bits as chmod writes them: "755", "644"; "" on Windows, which has none
f.mode(bits)sets them: three digits from 0 to 7 (error 11 if not); nothing on Windows
  • The three digits are for the owner, the group and everyone else: 4 to read, 2 to write and 1 to run, added up. "755" lets everyone read and run the file, and only its owner change it; "600" keeps it to its owner.
  • A copy keeps the permission bits (copy), not the time.

The parts of a path

f: file = file("reports/2024/january.csv")
print(f.name())
print(f.ext())
print(f.folder())
print(f.folder().folder())
print(file("notes").ext() == "")

Output:

january.csv
csv
folder("reports/2024")
folder("reports")
true
  • ext() is what follows the last . of the name, without it: "gz" for archive.tar.gz. A name without one, or that only starts with one (.bashrc), has "".
  • folder() of a name without a folder is folder("."), the folder the program runs in. The root has no folder above it: folder("/").folder() is folder("/").

Where this file is

file.this() is the .luma file it is written in, with its whole path. A program can find the files that belong to it, wherever it is started from:

print(file.this().name())
settings: file = file.this().folder().file("settings.json")

Output:

example.luma
  • In a file that another one imports, it is that file: a module in lib/ finds its own files with file.this().folder().
  • A built program keeps the path each .luma file had when it was built. Run elsewhere (on another computer), those files may not be there: a program that is shipped should find its files another way, for example from a flag.

Reading: the type decides

Like prompt, read gives what the variable it goes into needs:

f: file = file("data.txt")
f.write("one\ntwo\nthree\n")

text: str = f.read()
lines: [str] = f.read()
bytes: [byte] = f.read()
print(len(lines))
print(lines[1])
print(len(bytes))

Output:

3
two
14
  • A str is the whole file, exactly as it is.
  • A [str] is one element per line, without the line breaks. Both \n (Linux, macOS) and \r\n (Windows) work. A line break at the end doesn’t add an empty line, so "one\ntwo\n" and "one\ntwo" both give ["one", "two"]. An empty file gives [].
  • A [byte] is every byte, for files that aren’t text. For large ones, or to read numbers and fields out of them, use a buffer.

Where no particular type is expected, as in print(f.read()) or "${f.read()}", it’s a str.

Writing

write replaces everything in the file. A [str] is written with a line break after each line, so lines read with read can be changed and written back:

todo: file = file("todo.txt")
todo.write("milk\nbread\n")
items: [str] = todo.read()
items[] = "eggs"
items[0] = "oat milk"
todo.write(items)
print(todo.read())

Output:

oat milk
bread
eggs

A [byte] is written byte for byte:

data: [byte] = [76, 117, 109, 97]
file("word.bin").write(data)
print(file("word.bin").read())

Output:

Luma

Text is stored exactly as it is in the program: Luma strings are UTF-8, so "öö" takes 4 bytes in the file.

Adding lines: logs

add puts a line at the end of the file, without reading or rewriting what is already there. It’s the way to keep a log:

log: file = file("app.log")
[1, 2, 3].walk(n) {
    log.add("step ${n} done")
}
print(log.read())

Output:

step 1 done
step 2 done
step 3 done

add always writes \n after the line, also on Windows.

Checking, deleting, size

f: file = file("temp.txt")
print(f.exists())
f.write("12345")
print(f.exists())
print(f.size())
f.delete()
print(f.exists())

Output:

false
true
5
false

exists() is true only for a file: for a folder it’s false.

When something goes wrong

A missing file, a folder that isn’t there, or a file the program isn’t allowed to touch raises an error. Without a try, the program stops:

config: str = file("config.txt").read()

Output:

example.luma:1:34: runtime error: file not found: config.txt

With try, the program can go on, for example with a default:

config: str = "default settings"
err: error = nil
try err {
    config = file("config.txt").read()
}
print(config)

Output:

default settings

Or check first with exists():

settings: file = file("settings.txt")
if !settings.exists() {
    settings.write("volume=5\n")
}
print(settings.read())

Output:

volume=5
CodeMessageWhen
8file not found: notes.txtread, size or delete of a file that isn’t there
9cannot write data/notes.txt: the folder does not existwrite or add into a folder that isn’t there
9cannot read notes.txt: permission deniedthe operating system doesn’t allow it
9cannot read photos: it is a folderthe path is a folder, not a file
9cannot write notes.txt: the disk is fullno room left
9cannot add to : invalid file namean empty path
9cannot delete notes.txt: a program has it openWindows: a program (this one too) has the file open without sharing it
9cannot read notes.txt: a program has locked part of itWindows: a program locked the bytes
9cannot read x: error 36anything else, with the operating system’s error number

The operation in the message is read, write, add to, delete or get the size of; for a handle also open, cut, sync, lock and map, and two more reasons: invalid position (a negative position or count) and it is closed.

Reading and writing in place: open

The methods above work on a whole file. For large files and file formats, such as a database’s, f.open() gives a handle: the file stays open, and the program reads and writes bytes at any position in it.

h: handle = file("scores.bin").open()
h.write(0, "LUMA")                  // 4 bytes at the start
rec: buffer = buffer()
rec.write(1234, 4)
h.write(8, rec)                     // 4 more at position 8 (4 to 7 become 0)
print(h.size())
magic: str = h.read(0, 4)
back: buffer = h.read(8, 4)
n: int = back.read(4)
print("${magic} ${n}")
h.close()

Output:

12
LUMA 1234
MethodWhat it does
f.open()opens the file to read and write it, making it if it isn’t there. A file that may only be read is opened for reading, and writing to it raises error 9.
h.read(at, n)n bytes from position at, as a str, a [byte] or a buffer, whichever it goes into; fewer at the end of the file, nothing past it
h.map(at, n)a buffer on n bytes from position at, the same bytes read gives, mapped instead of read
h.write(at, data)writes a str, a [byte] or a buffer at position at, making the file longer if needed
h.size()the size in bytes
h.cut(n)makes the file n bytes long, dropping the rest
h.sync()waits until what was written is on the disk, not just in the system’s memory. A database does this before it says a change is saved, so that a power cut can’t lose it.
h.close()closes the file; again does nothing. A handle that nothing holds anymore is closed by itself.

Positions start at 0. print shows a handle as handle(scores.bin).

Mapping a file into memory: map

h.map(at, n) gives a buffer whose bytes are the file’s own, as the system keeps them in memory: nothing is read until it is used, and only the parts that are. Programs that map the same file share those pages, and the system can drop them and read them again when it needs the memory, as they’re in the file. It is for large files read many times, such as a model’s weights (the llama mod maps them).

  • Changing the buffer doesn’t change the file: writing to it makes the bytes the program’s own, a copy.
  • The buffer stays after the handle is closed.
  • The file must not get shorter while it is mapped: if another program cuts it, using bytes past the new end stops the program (the system’s SIGBUS), as it does any program that maps a file.
  • On Windows, luma run reads the bytes instead; a built program maps them there too.

Locks

Several programs can open the same file. To keep them from changing it at the same time, a program locks a range of bytes first. A lock doesn’t stop reading or writing; it is an agreement between the programs that ask for it:

h: handle = file("shared.db").open()
if h.own(0, 1) {
    h.write(100, "mine")
    h.release(0, 1)
} else {
    print("another program is writing")
}
h.close()
MethodWhat it does
h.share(at, n)a shared lock on the n bytes from at: many programs can hold one together, to read. false if another program owns them.
h.own(at, n)an exclusive lock: false if any other program holds a lock there
h.release(at, n)lets the lock go
  • They never wait: they answer at once whether the program got the lock.
  • The bytes don’t have to exist: programs often agree on a place past the end of the file.
  • Closing the handle, or the program ending, lets all its locks go.
  • These are the system’s own locks (fcntl on Linux, LockFileEx on Windows), the ones SQLite uses, so a Luma program can work together with other programs on the same files.
  • On Windows the system enforces them: while a handle owns bytes, another one that reads or writes them gets error 9, a program has locked part of it (bytes shared can be read, but not written). So keep locks on bytes the programs agree on, as SQLite does, not on the data itself.
  • A lock belongs to its handle: two handles of one file in a program lock as two programs would (one’s own is false while the other holds the bytes), and closing one handle keeps the other’s locks. (On macOS and the BSDs, where luma run uses POSIX locks, locks belong to the program instead: open a file once there and share the handle.)

Files are values

A file can be kept in variables, lists and maps, and printed:

files: [file] = [file("a.txt"), file("b.txt")]
files.walk(f) {
    f.write("hello")
}
print(files)
print("${files[0]} has ${files[0].size()} bytes")

Output:

[file("a.txt"), file("b.txt")]
file("a.txt") has 5 bytes

Files can’t be compared with ==, and they can’t be map keys or set elements.

Not available yet

  • Making and reading links.

See Limitations.