errors and exception

Chris Rebert clp2 at rebertia.com
Mon Aug 16 09:42:17 CEST 2010


On Mon, Aug 16, 2010 at 12:29 AM, Gary Herron
<gherron at islandtraining.com> wrote:
> On 08/16/2010 12:06 AM, Alan wrote:
>> Hello,
>> I am using things like:
<snip>
>> with open("myfile.txt") as f:
>>     for line in f:
>>         print line
>
> You don't need the new fangled with statement if you want to be compatible
> with older versions of Python2.  (It's nice and convenient, but not
> necessary.)
>
> f = open("myfile.txt")
> for line in f:
>   print line
> f.close()   # This is what the "with" statement guarantees; so now just do
> it yourself

Well, technically the equivalent would be:

f = open("myfile.txt")
try:
    for line in f:
        print line
finally:
    f.close()

It's just that the for-loop and print happen to be extremely unlikely
to throw exceptions; presumably the OP's actual code is more complex.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list