[Tutor] Problems with changing directory.

Michael Janssen Janssen at rz.uni-frankfurt.de
Sun Aug 22 17:33:27 CEST 2004


On Sun, 22 Aug 2004, David Holland wrote:

> def change_dir():
>     y = '/home/david/Documents/pyprogamming/test/'
>     try:
>         os.chdir(y)
>         print "line 53"
>         list_of_files = os.listdir(y)
>         print "line 55"
>         for file in list_of_files:
>             print "line 57"
>             linesone = open_files(file)
>             getlineinfo(linesone)
>             print file
>         print "Directory", y,"does exist"
>     except:
>         print y, "does not exist"

You need to make your exception handling more accurat: within your
try-except-clause many things can throw exceptions and nothing indicate it
was actually your os.chdir call. So narrow it:

try: os.chdir(y)
except:
    print "Error with os.chdir"
    # do something to terminate the function
    return

even better:

try: os.chdir(y)
except Exception, msg:
    print "Error with os.chdir:", msg

it's also common to name the expected Exception:

try: os.chdir(y)
except OSError:
    print y, "does not exists"

This help in cases, where you make a silly syntax-error or some such,
cause you will see the originaly python traceback for any other error than
OSError. Otherwise, when OSError gets raised, you can be quite confident
that this is due to a missing directory even without grabbing the error
message as "msg" in former example.

Michael


More information about the Tutor mailing list