Week5: Files & Exceptions -- First Look

Text files are collections of lines of text (strings) from Python's point of view. We frequently want to read a file, process that data, and then write the results in another file. We include a brief introduction to exception handling because it offers a clean way to prompt for a file name until you get a valid one.

Readings from the book The Practice of Computing Using Python.

Chapter 6: Files & Exceptions I


  1. Files
  2. Text files are collections of lines of text (strings) from Python's point of view. Our primary interaction is to open a file for reading ("r") and then use for to iterate through the file one line at a time.

      file_obj = open(filename_str,"r") 
      for line in file_obj: 

    We process the data we read, open another file for writing ("w") and write data to that file. It is critically important to close a file after writing to it.
      file_obj_out = open(filename2_str,"w") 

    1. Files (Video)
  3. Exceptions
  4. Exceptions provide a new type of control that is useful for checking the validity of input, e.g. valid filename, valid floating-point number, etc. You try some code and if a particular error is raised, you handle it (in the except suite).

      except SomeError:
    1. Exceptions (Video)
  5. Example
    1. Example reading and writing a file (Video I ) (Video II )
    2. Read the file tobe.txt, count the words, and then write the count to the file tobeOut.txt.

  6. Chapter 6 Exercises on Mimir
  7. Lab05 (do pre-lab first on D2L)