Newbie question: Any way to improve this code?

Peter Otten __peter__ at web.de
Fri Dec 5 22:11:46 EST 2003


Duncan Smith wrote:

> try:
>     f = open("firmas.txt",'r')
>     texto = f.read()
>     frases = texto.split('\n')[:-1]
> finally:
>     f.close()

Running this with a nonexistent firmas.txt gives you:

...> python frases.py
Traceback (most recent call last):
  File "frases.py", line 6, in ?
    f.close()
NameError: name 'f' is not defined

Although it looks less symmetrical, the f = open() should be placed *before*
the try block. When you enter the try block, you are already sure that the
file was opened, and only then it makes sense to ensure that the file will
be closed even if some of the following operations fail.  
frases = ... does not need access to the file and thus belongs *after* the
finally block - but that is less crucial.

Another (minor) issue: I'm never confident that a plain text file ends with
a newline character, so in my opinion you risk losing la última frase.

Peter




More information about the Python-list mailing list