[Tutor] help

Kirby Urner urnerk@qwest.net
Wed, 10 Oct 2001 20:45:39 -0700


At 04:05 PM 10/10/2001 -0700, james middendorff wrote:

>I have fixed my last post but I do have a question, I would like to keep 
>looping this over and over until you type quit,thanks for the help!

What might trigger an ioerror is the program tries to
open a file that doesn't exist.  That's all you need
to trap with the try: except: syntax.

The stuff about raw_input doesn't really need to be
in a try block.

In other words, this would work better:

   def getfile():
        import os, sys
        while 1:  # endless loop
           filename = raw_input("What file? ('q' to quit): ")
           if filename == 'q':
               break  # escape from loop
           try:
                inp = open(filename,"r")
                print # blank line
                for line in inp.readlines():
                     print line,  # note comma to suppress extra \n
           except IOError:
                 print "That's not a real file!"

        # upon exiting to loop, flow continues here
        sys.exit()  # I comment this out cuz I'm in shell mode

   >>> getfile()
   What file? ('q' to quit): duh.txt
   That's not a real file!
   What file? ('q' to quit): readme.txt

   This is Python version 2.2
   ==========================

   Copyright (c) 2001 Python Software Foundation.
   All rights reserved.

   Copyright (c) 2000 BeOpen.com.
   All rights reserved.
   ...

Kirby