try/except with multiple files

Matimus mccredie at gmail.com
Thu Jun 21 15:11:51 EDT 2007


It depends, what are you going to do if there is an exception? If you
are just going to exit the program, then that works fine. If you are
going to just skip that file, then the above wont work. If you are
going to return to some other state in your program, but abort the
file opening, you might want to close any files that were opened. The
closing can be taken care if in the except block, but you will have to
know which ones opened successfully.

In general I would do something like this for multiple files:

[code]
filenames = ["fname1","fname2","fname3"]
for fn in filenames:
    try:
        f = open(fn)
    except IOError:
        # handle exception
    #do something with f
[/code]

But, that might not work for you if the files aren't homogeneous (each
have similar contents). If the files have distinctly different
purposes, I would just wrap them each in their own try/except block.

I rambled a bit there, but I hope it helps.

Matt




More information about the Python-list mailing list