Comp 112

Lecture 12

Files and Exceptions



What Could Possibly Go Wrong?

There are many things that can go wrong in a program:

Some errors could be avoided by static analysis, which is analyzing the structure of a program without running it.

But others depend on the program interacting with the outside world and can’t be predicted.

Proceeding with Caution

One way to avoid errors is to use many conditional statements and only try to do things that we know will succeed.

Ploughing Ahead

But sometimes it’s easier to ask forgiveness than permission.

This style can make programs more clear and concise by focusing on the main execution path.

Try Statements

Raising Exceptions


Files and Paths

There are two different ways of specifying a path:

Files and Paths in Python

Opening Files

To open a file in Python, use the “open” function:

open (<path> , <mode>)

The open function takes two arguments:

The modes we care about for now are:

If a call to open is successful then it will return a filehandle object.

This is a token representing your right to read from or write to the file.

File Handling Exceptions

File Input

File Output

The Read-Modify-Write Pattern

A common pattern of working with files is to:

To Do This Week: