The textbook required for this Lecture is Starting Out with Python, 5th Edition (Global) by Tony Gaddis
Reading the indicated chapter(s) is required before class
This week covers Chapter 6 - Files and Exceptions from the textbook
Files
So far, programs have been entirely "self-contained" with no storage or data kept between each run. Files on the computer's hard drive allow programs to retain data, receive input or store output.
Types of files programs can use
Settings and configuration files
"Office Suite" files
Media files
Cache and cookie files
Assets, save files and replays
Text files
Simply contain text, encoded in ASCII or Unicode, and can be opened by programs like Notepad. The extension is not necessarily ".txt".
Binary files
Not text-based and are designed to only be opened by a program that can use the data in that format. Includes everything that isn't a text file.
Working with files in a program
1. Open the file
2. Use the file (read, write, or both)
3. Close the file
Opening a file
Requires specifying the filename and the mode to open it in (read, write, append, read/write)
In Python, the built-in function "open()" opens a file and returns a file object
Opening a file in different programming languages
Python: f = open('file.txt', 'r')
Java: FileReader f = new FileReader("file.txt");
PHP: $f = fopen('file.txt', 'r');
C/C++: FILE *f = fopen("file.txt", "r");
Ruby: f = File.open('file.txt', 'r')
Modes in Python
r (read only), w (write only), a (append), r+ (read and write), w+ (read and write), a+ (append and read/write)
Adding "b" after a mode opens the file in binary mode
Illustrating different file modes in Python
r: Error when trying to write
File created/emptied, "an" written to start
"an" added to end
r+: "an" written to start
w+: "an" written to start
a+: "an" added to end
Writing to a file
Use the "write" method/function of the file object
Can insert line breaks using "\n"
Closing a file
Must be done to ensure data is saved and the file is unlocked for other programs
The "Test Generator" case study was reviewed from last week
Modifying the "Test Generator" program to write output to a file
Prompt user for + or -
Create and open "output.txt" file in write mode
Write test type, name, and questions to the file
Close the file
Print message informing user of the file
Expressions
1 + 8
9 + 2
5 + 4
6 + 4
7 + 2
5 + 3
2 + 1
9 + 7
The result of 1 + 8 is 9
The result of 9 + 2 is 11
The result of 5 + 4 is 9
The result of 6 + 4 is 10
The result of 7 + 2 is 9
The result of 5 + 3 is 8
The result of 2 + 1 is 3
The result of 9 + 7 is 16
Raised
Triggered or thrown (depending on the language)
Termination
The program may be unable to continue, hence the response will be to display an error message and end in a clean manner
Continuation
The program may be able to continue, e.g. re-prompting for input or performing some other action to work around the exception
Exception handling
Another control structure, like selection and iteration (loop) statements, that allows you to control the flow of execution in a program when an exception occurs, transferring control to an exception handler
So far in the unit, we have not handled the majority of exceptions that could occur in the code we have written
We've assumed that the user enters a number when prompted to enter a number (which can then be converted to an int/float without an exception occurring)
This has been to keep our code simple and understandable, avoiding added complexity while we are learning the basics
We have implemented exception handling on occasion, e.g. re-prompting for input until a number is typed
It is important that you consider (and handle) the exceptions that could potentially occur in the code that you write
Basic Exception Handling - Termination
1. Prompt for a number and try to convert it to an integer
2. If a ValueError exception is raised, print an error message and use sys.exit() to end the program
3. If the exception is not raised, continue to print "You typed"
Basic Exception Handling - Continuation
1. Prompt for a number and try to convert it to an integer
2. If a ValueError exception is raised, just put an integer of 7 into the num variable
3. Continue to print "You typed"
Basic Exception Handling - Continuation
1. Place the try/except code inside an endless loop
2. If a ValueError exception is raised, go to the exception handler and print an error message
3. If the exception is not raised, reach the break statement and end the loop