[Tutor] "=" invalid syntax ?

Daniel Ehrenberg littledanehren at yahoo.com
Sat Jan 31 14:09:17 EST 2004


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/



More information about the Tutor mailing list