Reading¶
(3h)
Until p.401, not including programming exercises.
Concepts:
6.1 Introduction to File I/O
Motivation: read from the file at a later time
Opening, processing, closing a file
Types of files
File access methods, sequential, direct. We will use sequential
Opening a file
f = open(filename, mode)read,write,append
Specifying the location of a file
Use
rin Windowsr'C:\Users\...
Writing data to a file
f.write(string)f.close()
Reading data from a file
contents = f.read()
Concatenating a newline to a string
"string" + "\n"
Reading a string and stripping a newline from it
string.rstrip('\n')
Appending data to an existing file
f = open("file.txt", "a")
Writing and reading numeric data
str(number)
6.2 Using loops to process files
Reading a file with a loop and detecting the end of the file
f.readline(); while line != ""; f.readline()
MORE CONVENIENT using
forfor line in f:
Spotlight: Working with files
6.3 Using the
withstatement to open filesa resource typically goes through open, work, close.
with open("filename", mode) as f:multiple:
with open() as f1, open() as f2:
6.4 Processing records
for each data, use a new line
Examples: Adding and displaying records, searching for a record, modifying records (creating a temp file and deleting it), deleting records
6.5 Exceptions
exceptions make the program halt.
try exceptallows graceful handlingtry: statements that can make the program halt except Exception: graceful handlinglook before you leap (LBYL) vs easier to ask forgiveness than permission (EAFP)
Examples: dividing by zero, wrong input (
int("hello"))Multiple exceptions:
except, except ...Displaying an exception’s default error message:
except Ex as errelseblock: only if no exceptions have occurredfinallyWhat if an exception is not handled?