Opening files without closing them

3c273 nospam at nospam.com
Wed Mar 8 19:48:02 CET 2006


"Peter Hansen" <peter at engcorp.com> wrote in message
news:mailman.2850.1141759783.27775.python-list at python.org...
>
> So this is better, though probably excessive in small scripts:
>
> try:
>      f = open('file')
> except IOError:
>      # do something else
> else:
>      try:
>          content = f.read()
>      finally:
>          f.close()
>
> This takes advantage of "else" on try statements, which executes only if
> the except statement is not executed.
>
Thank you for your reply. I had forgotten that you could use 'else' in a
'try' statement. I like this solution. Thanks again.
Louis





More information about the Python-list mailing list