[Tutor] "=" invalid syntax ?

Karl Pflästerer sigurd at 12move.de
Sat Jan 31 16:24:37 EST 2004


On 31 Jan 2004, Daniel Ehrenberg <- littledanehren at yahoo.com wrote:

> In Python, = is a statement. You can still loop
> through files, however. Here's how I would write the
> program instead:

> #!/usr/bin/python

> try:
>     fi = open('test.py', 'r')
>     for line in fi:
>         print line
> except IOError:
>     print "Can't open file for reading."
> finally:
>     fi.close()

A little nitpick (I wrote try/except some time exact like the above till
I read a posting from Alex Martelli where he wrote about `else' in that
construct); IMO the above code with `else' is clearer:

try:
    fi = open('test.py', 'r')
except IOError:
    print "Can't open file for reading."
else:
    for line in fi:
        print line
finally:
    fi.close()

Now you see at first glance what you try to do, what happens if it fails
and what happens if it succeeds.


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list




More information about the Tutor mailing list