try/except with multiple files

Robert Hicks sigzero at gmail.com
Thu Jun 21 15:13:45 EDT 2007


On Jun 21, 3:11 pm, Matimus <mccre... at gmail.com> wrote:
> 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

Helps a bunch...thank you very much.

Robert




More information about the Python-list mailing list