[Tutor] "=" invalid syntax ?

Lloyd Kvam pythontutor at venix.com
Sat Jan 31 16:37:31 EST 2004


try/except and try/finally are two different forms.  There is no try/except/finally.

(thanks to Alex Martelli) it should look more like:

try:
     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()

The else is a convenient to limit the scope of the try statement.

The exceptions chapter of "Python in a Nutshell" has very lucid descriptions
of exception handling strategies.

Daniel Ehrenberg wrote:
> Xuer wrote:
> 
>>print all lines of a simple file
>>
>>test.py
>>-----------------------------------------------
>>#!/usr/bin/python
>>
>>try:
>>        fi = open('test.py', 'r')
>>except IOError:
>>        print 'Can\'t open file for reading.'
>>        sys.exit(0)
>>while (line=fi.readline()):
>>        print line
>>-----------------------------------------------
>>then run it
>>
>>$./test.py
>>  File "./test.py", line 8
>>    while (line=fi.readline()):
>>               ^
>>SyntaxError: invalid syntax
>>
>>what's the problem?
>>
>>thanks and regards :)
> 
> 
> 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()
> 
> Daniel Ehrenberg
> 
> __________________________________
> Do you Yahoo!?
> Yahoo! SiteBuilder - Free web site building tool. Try it!
> http://webhosting.yahoo.com/ps/sb/
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582




More information about the Tutor mailing list