An Exceptional Writer

Calvin (Deutschbein)
Slides by Jed Rembold

9 March 2022

Announcements

  • Project 2 due on Friday!
  • Project 1 feedbacks coming out!

Review!

To the right are the contents of a text file named PBride.txt. Which code snippet below would print off the word “father”?

My name is Inigo Montoya.
You killed my father.
Prepare to die.
with open('PBride.txt') as f:
    for line in f:
        w = line.split()
        if w[0] == "You":
            print(w[-1])
with open('PBride.txt') as f:
    c = f.read().splitlines()
    print(c[1][4])
with open('PBride.txt') as f:
    c = read('PBride.txt')
    print(c.find("father"))
with open('PBride.txt') as f:
    c = f.read()
    i = c.find("f")
    print(c[i:i+6])

Aren’t you Exceptional

  • When opening a file for reading, it is possible the file does not exist!
    • Python handle this (and many other potential errors that can arise) using a mechanism called exception handling
    • Common on other languages as well
  • An exception is a object that belongs to an overarching hierarchy of exception classes
    • Different classes/types for different purposes
    • File operations, for example, use the exception class IOError
  • If open encounters an error, it reports the error by raising an exception with IOError as its type.
    • Raising an exception generally immediately terminates your program, but sometimes that is undesirable

Ignore Yoda, there is a try

  • Python uses the try statement to indicate an interest in trying to handle a possible exception
  • In simplest form, the syntax is:
try:
    # Code that may cause an exception
except type_of_exception:
    # Code to handle that type of exception
  • type_of_exception here is the class name of the exception being handled
    • IOError for the file reading errors we are discussing
  • Any exceptions arising from within the try block or within functions called within the try block would be “caught”

Example: Requesting Existing File

  • As an example, the below function will repeatedly ask the user to supply a file name that actually exists.
  • It will not just immediately break should they give it an invalid filename!
def get_existing_file(prompt="Input a filename: "):
    while True:
        filename = input(prompt)
        try:
            with open(filename):
                return filename
        except IOError:
            print("That filename is invalid!")
  • If the open call succeeds, we immediately just return the filename, but if it fails due to a IOError, we display a message and then keep asking

Choosing Wisely

  • The Python package used to implement pgl.py also supports a mechanism to choose files interactively, made available through the filechooser.py library module.
  • filechooser.py exports two functions:
    • choose_input_file for selecting a file
    • choose_output_file for selecting a folder and filename to save a file to
  • Both open up a file dialog that lets you select/choose a file
    • Clicking Open or Save returns the full pathname of the file
    • Clicking Cancel returns an empty string

Writing Text Files

  • You can write text files using almost the same syntax as reading:
with open(filename, mode) as file_handle:
    # Code to write the file using file_handle
  • Note the mode parameter to open here! Mode is a string which is either
    • "w" to write a new file (or overwrite an existing file)
    • "a" to append new contents to the end of an existing file
  • The file handler supports the methods:
    • .write(some_string) to write a string to the file
    • .writelines(iterable_of_strings) to write each iterable element to the file

Writing ASCII SINE

  • Suppose I wanted to try my hand at some ASCII art and fill a text file with a vertical oscillating sine wave
  • A sine wave generally looks like: \[ A \sin\left(\frac{2\pi}{T}x\right)\] where \(A\) is the amplitude of the wave and \(T\) the period of the wave, or how quickly it repeats
  • How can we put this together?

Tabulation

  • Arrays can also be useful when you have a set of values and you need to count how many values fall into a different ranges
    • Process is called tabulation
  • The idea is that for each data file we encounter, we figure out a corresponding index in our tabular array and then increment the value of that element
  • Your book shows this for seeing how many times each letter of the alphabet appears in a text sequence
  • Let’s instead look at an example of distances between cities in western North America.

Multidimensional Arrays

  • We know that elements of a list can be lists in and of themselves. If the lengths of all the lists making up the elements of a list remain fixed, then the list of lists is called a multidimensional array
  • In Python, we can create multidimensional arrays just be creating lists of constant length as the elements to another list
magic = [ [2, 9, 4], [7, 5, 3], [6, 1, 8] ]
  • We can always get the individual element of one of the inner lists by using 2 indices.
    • magic[1][1] = 5
    • magic[-1][0] = 6

Picturing Multidimensional Arrays

  • Multidimensional arrays are general pictured as each inner list being stacked beneath the previous
  • As such, the outermost elements/indices represent the row, and the inner elements/indices represent the column [ [2, 9, 4], [7, 5, 3], [6, 1, 8] ]


Initialize a Chessboard

image/svg+xml

// reveal.js plugins