Opening a file
The mode decides what open() may do to the file
'r' reads. 'w' erases and writes. 'a' adds to the end.
A program reaches a file through open, and the mode says what it intends to do. Here is a file with two lines. Open it with r, to read. Nothing changes. Open it with w, to write. The contents are erased the moment it is opened, before you write anything. Open it with a, to append. The contents stay, and whatever you write goes after them.
Opening a file · Going deeper
Reading and writing
read(), readline(), readlines(), or a loop.
The with statement
with closes the file for you, even after an error
with open(...) as f: closes f when the block ends.
A file that was opened must be closed. The with statement takes care of that. It opens the file and gives it the name f. Inside the block, you use f. When the indented block ends, Python closes the file. So this prints True. The older way works too, but you must remember the close yourself.
The with statement · Going deeper
What goes wrong with files
A missing file is a FileNotFoundError.
Check yourself
What does this print?
CSV files
csv.reader turns each line into a list of strings
One line, one list. Every field is a string.
A CSV file is a table saved as text. The csv module reads it for you. The first line becomes a list of two strings. The header gets no special treatment. So does the next. Notice that thirty six arrives as a string, not a number. And a value that contains a comma is kept whole, because the file puts it in quotes.
CSV files · Going deeper
Writing with csv.writer
writerow() writes one list as one line.
Modules and math
floor goes down, ceil goes up, trunc goes towards zero
import math, then math.floor(), math.ceil(), math.trunc(), math.sqrt().
A module is a file of ready made functions. You bring it in with import, and reach inside with a dot. Here is the math module. Take two numbers, two and a half and minus two and a half. Floor moves down to the whole number below: two, and minus three. Ceil moves up: three, and minus two. Trunc cuts off the fraction, which moves towards zero: two, and minus two. And the square root always comes back as a float.
Modules and math · Going deeper
Ways to import, and what goes wrong
import, from ... import, as.
Check yourself
What does this print?
The random module
random differs on every run, unless you set a seed
random(), choice(), sample(), seed().
The random module makes choices for you. Random gives a float, at least zero and less than one. Choice picks one item from a sequence. Sample picks several different items, and returns them as a list. Run the program again and all three change. Unless you call seed first. The same seed gives the same results, every time.
The random module · Going deeper
What random can and cannot give
Reason about the range, not the value.
Check yourself
Which values can this print?
Lesson complete
You finished “Files and modules”
Answer the questions along the way to see your score here.