Page 64 - Programming the Raspberry Pi Getting Started with Python
P. 64

The line f.close() has been added. You should always call the close command when you are done
          with a file to free up operating system resources. Leaving a file open can lead to problems.
             The  full  program  is  contained  in  the  file  06_01_hangman_file.py,  and  a  suitable  list  of  animal
          names can be found in the file hangman_words.txt. This program does nothing to check that the file
          exists before trying to read it. So, if there file isn’t there, we get an error that looks something like

          this:






             To make this a bit more user friendly, the file-reading code needs to be inside a try command, like
          this:











             Python will try to open the file, but because the file is missing it will not be able to. Therefore, the
          except part of the program will apply, and the more friendly message will be displayed. Because we

          cannot  do  anything  without  a  list  of  words  to  guess,  there  is  no  point  in  continuing,  so  the exit
          command is used to quit.
             In writing the error message, we have repeated the name of the file. Sticking strictly to the Don’t
          Repeat Yourself (DRY) principle, the filename should be put in a variable, as shown next.  That way, if
          we decide to use a different file, we only have to change the code in one place.















             A  modified  version  of  Hangman  with  this  code  in  it  can  be  found  in  the  file

          06_02_hangman_file_try.py.
          Reading Big Files
          The way we did things in the previous section is fine for a small file containing some words. However,
          if we were reading a really huge file (say, several megabytes), then two things would happen. First, it
          would take a significant amount of time for Python to read all the data. Second, because all the data is
          read at once, at least as much memory as the file size would be used, and for truly enormous files, that
          might result in Python running out of memory.
             If you find yourself in the situation where you are reading a big file, you need to think about how
          you are going to handle it. For example, if you were searching a file for a particular string, you could
          just read one line of the file at a time, like this:
   59   60   61   62   63   64   65   66   67   68   69