Opening a file

The mode decides what open() may do to the file

notes.txt holds two lines: one, twothe file just after openingopen('notes.txt', 'r')one, tworead: the file is unchanged, and must existopen('notes.txt', 'w')emptywrite: the old contents are erased at onceopen('notes.txt', 'a')one, twoappend: whatever you write is added at the endThe mode decides what open() may do to the file.open() returns a file object. The second argument is the mode: 'r' to read, 'w' to writefrom scratch, 'a' to add to the end. Leave it out and you get 'r'. Both 'w' and 'a' createthe file if it does not exist.

'r' reads. 'w' erases and writes. 'a' adds to the end.

Opening a file · Going deeper

Reading and writing

f = open('notes.txt')The file holds two lines: one, twoCodeGivesNotef.read()'one\ntwo\n'The whole file as one stringf.read() again''Already at the end: an empty stringf.readline()'one\n'One line, with its new line characterf.readlines()['one\n', 'two\n']A list with one string per linefor line in f:'one\n', then 'two\n'A loop takes one line at a timeline.strip()'one'Removes the new line at the endf.write('three\n')6With w or a: writes text, returns the countA file object remembers how far it has read.Each read carries on from where the last one stopped. write() adds no new line of its own.

read(), readline(), readlines(), or a loop.

The with statement

with closes the file for you, even after an error

with open('notes.txt', 'a') as f: f.write('three\n')print(f.closed)opens the file to append, and names it fadds a third line to the filethe block has ended, so the file is already closed: prints TrueWithout with, you close it yourself:f = open('notes.txt', 'a'); f.write('three\n'); f.close()with closes the file for you, even after an error.A file must be closed for its writes to be safely saved. The with statement closes itwhen its indented block ends, however the block ends.

with open(...) as f: closes f when the block ends.

The with statement · Going deeper

What goes wrong with files

CodeGivesNoteopen('missing.txt')FileNotFoundErrorReading needs the file to existopen('missing.txt', 'w')a new, empty fileWriting and appending create itf.write('x') on a file opened with 'r'an error: not writableThe mode did not allow writingf.write(5)TypeErrorwrite() takes a string: use str(5)f.read() after the with blockValueErrorThe file is closedopen('notes.txt', 'w') to add a linethe old lines are lostThe classic slip: 'a' was meantPut the with statement under try, and add the branch except FileNotFoundError: to handle a missing file.Opening a file can fail, so it is a natural place for try and except.

A missing file is a FileNotFoundError.

Check yourself

with open('log.txt', 'w') as f: f.write('a')with open('log.txt', 'w') as f: f.write('b')with open('log.txt') as f: print(f.read())

What does this print?

CSV files

csv.reader turns each line into a list of strings

import csvwith open('people.csv', newline='') as f: for row in csv.reader(f): print(row)a line of people.csvrowname,age['name', 'age']the header is a row like any otherAda,36['Ada', '36']every value is a string: '36', not 36"Lee, Sam",41['Lee, Sam', '41']quotes keep a comma inside one valuecsv.reader turns each line of the file into a list of strings.CSV means comma-separated values: one record per line, commas between the fields.To calculate with a field, convert it first: int(row[1]).

One line, one list. Every field is a string.

CSV files · Going deeper

Writing with csv.writer

import csvwith open('people.csv', 'w', newline='') as f: writer = csv.writer(f)Then, inside the blockLine writtenNotewriter.writerow(['name', 'age'])name,ageOne list in, one line outwriter.writerow(['Ada', 36])Ada,36Numbers are written as textwriter.writerow(['Lee, Sam', 41])"Lee, Sam",41Quotes are added where they are neededcsv.writer does the reverse: each list becomes one line of the file.newline='' in open() is what the csv documentation asks for, so the module can manage theline endings itself. The file modes work as before: w starts again, a adds rows.

writerow() writes one list as one line.

Modules and math

floor goes down, ceil goes up, trunc goes towards zero

import math-3-2-101232.5-2.5floorfloormath.floor(2.5) is 2math.floor(-2.5) is -3ceilceilmath.ceil(2.5) is 3math.ceil(-2.5) is -2trunctruncmath.trunc(2.5) is 2math.trunc(-2.5) is -2math.sqrt(16)is 4.0, a floatfloor goes down, ceil goes up, trunc goes towards zero.After import math, its functions are reached with the module name and a dot.

import math, then math.floor(), math.ceil(), math.trunc(), math.sqrt().

Modules and math · Going deeper

Ways to import, and what goes wrong

You writeThen you callNoteimport mathmath.sqrt(16)The whole module: module name, dot, functionfrom math import sqrtsqrt(16)One name, used directlyfrom math import sqrt, ceilceil(sqrt(10)) is 4Several names at onceimport math as mm.sqrt(16)The module under a shorter nameWhat goes wrongGivesimport math, then sqrt(16)NameErrorOnly the name math was createdfrom math import sqrt, then math.piNameErrorOnly the name sqrt was createdimport mathsModuleNotFoundErrorNo module of that namemath.sqrt(-1)ValueErrorNo real square rootAn import creates exactly the names you wrote, and no others.

import, from ... import, as.

Check yourself

import mathprint(math.floor(-1.5) + math.ceil(1.5))

What does this print?

The random module

random differs on every run, unless you set a seed

import randomone possible resultrandom.random()0.13436424411240122a float from 0.0 up to, but never, 1.0random.choice([10, 20, 30])10one item of a sequencerandom.sample([1, 2, 3, 4, 5], 2)[3, 1]a list of 2 different itemsrandom.seed(1)called first: the same three results on every runrandom gives different results on each run, unless you set a seed.The numbers are pseudorandom: worked out by a formula from a starting value, the seed.Give the same seed and the same sequence comes out again, which is what a test needs.

random(), choice(), sample(), seed().

The random module · Going deeper

What random can and cannot give

CodeGivesNoterandom.random()0.0 <= x < 1.0It can be 0.0 but is never 1.0random.choice('abc')'a', 'b' or 'c'Any sequence: a string works toorandom.choice([])IndexErrorNothing to choose fromrandom.sample([1, 2, 3], 2)two different itemsNo item is picked twice; the list is unchangedrandom.sample([1, 2], 3)ValueErrorMore items asked for than existint(random.random() * 6) + 11 to 6A dice roll from a floatrandom.seed(7) twice, same callsthe same resultsSame seed, same sequenceYou cannot say what random will print. You can say what it could print.For code that uses random, reason about the range and the type of the result.

Reason about the range, not the value.

Check yourself

import randomprint(random.choice([1, 2, 3]) * 2)

Which values can this print?

Lesson complete

You finished “Files and modules”

Answer the questions along the way to see your score here.

Back to Python Institute PCEP

Open in a new tab