DG_Bar_Blue_USLetter_RGB
Chapter 5
Files and
Exceptions I
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
hand.png
ostrich.png
What is a file?
A file is a collection of data that is storedon secondary storage like a disk or athumb drive
accessing a file means establishing aconnection between the file and theprogram and moving data between the two
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
hand.png
ostrich.png
Two types of files
Files come in two general types:
text files. Files where control characterssuch as "/n" are translated. This aregenerally human readable
binary files. All the information is takendirectly without translation. Not readableand contains non-readable info.
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
hand.png
ostrich.png
File Objects or stream
When opening a file, you create a fileobject or file stream that is a connectionbetween the file information on disk andthe program.
The stream contains a buffer of theinformation from the file, and provides theinformation to the program
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
hand.png
ostrich.png
Buffering
Reading from a disk is very slow. Thus thecomputer will read a lot of data from a filein the hopes that, if you need the data inthe future, it will be buffered in the fileobject.
This means that the file object contains acopy of information from the file called acache (pronounced "cash")
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
hand.png
ostrich.png
Making a file object
my_file = open("my_file.txt", "r")
my_file is the file object. It contains thebuffer of information. The open functioncreates the connection between the disk fileand the file object. The first quoted string isthe file name on disk, the second is the modeto open it (here,"r" means to read)
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
hand.png
ostrich.png
Where is the disk file?
When opened, the name of the file cancome in one of two forms:
"file.txt" assumes the file name isfile.txt and it is located in the currentprogram directory
"c:\bill\file.txt" is the fullyqualified file name and includes thedirectory information
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
hand.png
ostrich.png
Different modes
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
hand.png
ostrich.png
Careful with write modes
Be careful if you open a file with the 'w'mode. It sets an existing file’s contents tobe empty, destroying any existing data.
The 'a' mode is nicer, allowing you towrite to the end of an existing file withoutchanging the existing contents
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
hand.png
ostrich.png
Text files use strings
If you are interacting with text files (whichis all we will do in this book), rememberthat everything is a string
everything read is a string
if you write to a file, you can only write a string
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
hand.png
ostrich.png
writing to a file
Once you have created a file object, openedfor reading, you can use the print command
you add file=file to the printcommand
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
hand.png
ostrich.png
close
When the program is finished with a file, weclose the file
flush the buffer contents from thecomputer to the file
tear down the connection to the file
close is a method of a file obj
 file_obj.close()
All files should be closed!
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
j0441471.png
Code Listing 5.1
Reverse file lines
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
ExceptionsFirst Cut
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
hand.png
ostrich.png
How to deal with problems
Most modern languages provide methodsto deal with ‘exceptional’ situations
Gives the programmer the option to keepthe user from having the program stopwithout warning
Again, this is not about fundamental CS,but about doing a better job as aprogrammer
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
hand.png
ostrich.png
What counts as exceptional
errors. indexing past the end of a list,trying to open a nonexistent file, fetching anonexistent key from a dictionary, etc.
events. search algorithm doesn’t find avalue (not really an error), mail messagearrives, queue event occurs
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
hand.png
ostrich.png
exceptions (2)
ending conditions. File should be closed atthe end of processing, list should besorted after being filled
weird stuff. For rare events, keep fromclogging your code with lots of ifstatements.
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
hand.png
ostrich.png
Error Names
Errors have specific names, and Pythonshows them to us all the time.
You can recreate an error to find the
correct name. Spelling counts!
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
hand.png
ostrich.png
a kind of non-local control
Basic idea:
keep watch on a particular section of code
if we get an exception, raise/throw thatexception (let it be known)
look for a catcher that can handle that kindof exception
if found, handle it, otherwise let Pythonhandle it (which usually halts the program)
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
hand.png
ostrich.png
Doing better with input
In general, we have assumed that theinput we receive is correct (from a file,from the user).
This is almost never true. There is alwaysthe chance that the input could be wrong
Our programs should be able to handlethis.
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
hand.png
ostrich.png
Worse yet, input is evil
  "Writing Secure Code”, by Howard andLeBlanc
   “All input is evil until proven otherwise”
Most security holes in programs are basedon assumptions programmers make aboutinput
Secure programs protect themselves fromevil input
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
hand.png
ostrich.png
Rule 7
All input is evil, until proven otherwise
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
hand.png
ostrich.png
General form, version 1
try:
   suite
except a_particular_error:
   suite
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
hand.png
ostrich.png
try suite
the try suite contains code that we wantto monitor for errors during its execution.
if an error occurs anywhere in that trysuite, Python looks for a handler that candeal with the error.
if no special handler exists, Pythonhandles it, meaning the program halts andwith an error message as we have seenso many times 
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
hand.png
ostrich.png
except suite
an  except suite (perhaps multipleexcept suites) is associated with a trysuite.
each exception names a type of exceptionit is monitoring for.
if the error that occurs in the try suitematches the type of exception, then thatexcept suite is activated.
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
hand.png
ostrich.png
try/except group
if no exception in the try suite, skip allthe try/except to the next line of code
if an error occurs in a try suite, look forthe right exception
if found, run that except suite and thenskip past the try/except group to thenext line of code
if no exception handling found, give theerror to Python
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
j0441471.png
Code Listing 5.2
Find a line in a file
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
Counting Poker Hands
"The Practice of Computing Using Python",
Punch & Enbody, Copyright © 2013 Pearson Education, Inc.
hand.png
ostrich.png
Reminder, rules so far
1.Think before you program!
2.A program is a human-readable essay on problemsolving that also happens to execute on a computer.
3.The best way to imporve your programming andproblem solving skills is to practice!
4.A foolish consistency is the hobgoblin of little minds
5.Test your code, often and thoroughly
6.If it was hard to write, it is probably hard to read. Add acomment.
7.All input is evil, unless proven otherwise.