try...except...finally problem in Python 2.5

Paul Rubin http
Wed Feb 14 15:09:34 EST 2007


"redawgts" <redawgts at gmail.com> writes:
>         try:
>             f = file(self.filename, 'rb') ...
> Can someone tell me what's wrong with the code? 

Various people have explained the error: if the file open attempt
fails, f is never assigned.  Doing it the right way (i.e. handling the
potential exceptions separately) with try/except statements is messy,
so it's worth mentioning that 2.5 adds the new "with" statement to
clean this up.  I'm not using 2.5 myself yet so maybe someone will
have to correct me, but I think you'd write:

    from __future__ import with_statement

    self.isDataLoaded = False
    with open(self.filename, 'rb') as f:
        f.seek(DATA_OFFSET)
        self.__data = f.read(DATA_SIZE)
        self.isDataLoaded = True

and that should handle everything, closing the file automatically.



More information about the Python-list mailing list