23 Reading and Writing
A program is more useful when it can take something in and leave
something behind: lines typed at a keyboard or sent down a serial line,
words on the command line, files on a disk. This chapter covers all
three. print has been with us since the first page.
| To | Write | Gives |
|---|---|---|
| read a line typed | input(),
input("Name: ") |
str or none |
| read the command line | program.arguments() |
list[str] |
| read a file | files.read(path) |
str |
| write a file | files.write(path, text) |
nothing |
| add to a file | files.append(path, text) |
nothing |
| ask if a file is there | files.exists(path) |
bool |
| remove a file | files.remove(path) |
nothing |
23.1 print
print shows its values on one line, with a space between
them, and ends the line. Text is shown as it is; inside a list, it is
shown in quotes. To lay a line out exactly, build it with an
f string (Text):
let volts = 3.3
print("supply", volts, ["a", 1])
print(f"supply={volts:.2f}V")
print()
print("after an empty line")supply 3.3 ["a", 1]
supply=3.30V
after an empty line
23.2 Reading lines: input
input() reads the next line, without its line end. Given
a question, it prints the question first and stays on that line. When
there are no more lines, it gives none: at a keyboard that
is Ctrl-D (Ctrl-Z then Enter on Windows), and for a file sent in with
< it is the end of the file.
let name = input("Name: ")
if name is none {
print("nobody there")
} else {
print(f"Hello, {name}!")
}Name: Hello, Ada!
Here the line Ada was sent in rather than typed, so it
does not appear after the question as it would at a keyboard.
Because the answer may be none, it must be asked about
before it is used as text (Values That
May Be Missing). A loop that reads every line breaks on
none, and after that the checker knows the line is a
str:
var total = 0
while true {
let line = input()
if line is none {
break
}
try {
total += int(line.strip())
} except ValueError {
print("not a number:", line)
}
}
print("total", total)not a number: fast
total 49
Here the program was given four lines. Run it yourself and type them,
or put them in a file and send it in:
zeno run total.zeno < numbers.txt.
Python’s input() raises an error at the end of the
input, so a loop that reads everything needs a try.
none is the answer "there is no line", and the type makes
sure the program handles it. (Decision 6.18.)
On a board, a firmware C library usually ties the input to a serial
line, and then input() reads a line from the serial
port.
23.3 The command line
program.arguments() gives the words written after the
file, as a list of text. The program’s own name is not in it, so the
first word is [0]:
greet.zeno
import program
let names = program.arguments()
if len(names) == 0 {
print("usage: zeno run greet.zeno <names>")
}
for name in names {
print("hello,", name)
}hello, Ada
hello, Grace
With zeno run, every word after the file belongs to the
program, even one that looks like an option of Zeno’s; Zeno’s own
options go before the file: zeno run --vm greet.zeno Ada. A
compiled program gets the same list from the words after its name:
./greet Ada Grace.
23.4 Files
import files
files.write("shopping.txt", "milk\neggs\n")
files.append("shopping.txt", "bread\n")
print(files.read("shopping.txt").lines())
print(files.exists("shopping.txt"))
files.remove("shopping.txt")
print(files.exists("shopping.txt"))["milk", "eggs", "bread"]
true
false
A file is read whole, as one str, and written whole.
There is no open and no close, so there is
nothing to forget to close. write makes the file, or
empties it first; append makes it, or adds to its end.
write and append put down exactly the text
they are given. A program that wants lines ends each with
"\n", and reads them back with lines(), which
knows both kinds of line end, so a file from Windows reads the same.
Opening and closing is a pair that every program must get right on every path, errors included, and a file left open is a classic leak. Reading and writing whole files covers what most programs do, with no pair to get wrong. Reading a large file in pieces needs an open file with an owner, and waits for a program that needs it. (Decisions 6.12 and 6.13.)
When a file cannot be used
A file that cannot be used raises a FileError, with a
message that says why:
| What happened | The message |
|---|---|
| nothing is at the path | there is no file `notes.txt` |
| it is a folder, or may not be read | cannot read `notes.txt` |
| it is not text | `notes.txt` does not hold text |
| it cannot be made or written | cannot write `notes.txt` |
| it cannot be removed | cannot remove `notes.txt` |
import files
function first_line(path: str) -> str raises FileError {
let lines = files.read(path).lines()
if len(lines) == 0 {
return ""
}
return lines[0]
}
try {
print(first_line("settings.txt"))
} except FileError as e {
print("no settings:", e.message)
}no settings: there is no file `settings.txt`
A missing file is not a mistake in the program: no check the program
could make beforehand rules it out, since another program may remove the
file in between. So FileError can always be caught, even in
a firmware build where other errors stop the program. A function that
uses a file says raises FileError, or catches it. (Decision
6.14.)
A file holds text
files.read gives a str, and a
str is characters, so the file must be UTF-8 text. A
picture or any other bytes are refused with a FileError.
Reading bytes is not in version 0.1.
23.5 A worked example: a log book
This program keeps a log of readings in a file. Each run adds the readings given on the command line, then prints every reading so far and their average:
logbook.zeno
import files
import program
let path = "readings.txt"
for word in program.arguments() {
try {
let value = float(word)
files.append(path, f"{value}\n")
} except ValueError {
print("skipped:", word)
}
}
var values: list[float] = []
if files.exists(path) {
for line in files.read(path).lines() {
values.append(float(line))
}
}
print(len(values), "readings:", values)
if len(values) > 0 {
print(f"average {sum(values) / float(len(values)):.2f}")
}$ zeno run logbook.zeno 21.5 22.0
2 readings: [21.5, 22.0]
average 21.75
$ zeno run logbook.zeno 23.5
3 readings: [21.5, 22.0, 23.5]
average 22.33
print writes a line. input() reads one, and
gives none when there are no more.
program.arguments() gives the words after the file.
files.read, write, append,
exists and remove work on whole files of text,
and every one but exists may raise a
FileError, which can always be caught.
Write a program that counts the lines, words and characters of the text sent to it with
<.Write
copy.zeno, which copies the file named by its first argument to the file named by its second, and says clearly what is wrong when it is given the wrong number of words.Keep a counter in a file: each run reads it, adds one, writes it back, and prints it. What should the first run do?
Try to read a picture with
files.readand read the message.