[Tutor] Why is it...

Jason Massey jason.massey at gmail.com
Thu Mar 22 20:05:04 CET 2007


In the interpreter this doesn't work:

>>> f = open(r"c:\python24\image.dat")
>>> line = f.readline()
>>> while line:
...     line = f.readline()
... f.close()
Traceback (  File "<interactive input>", line 3
    f.close()
    ^
SyntaxError: invalid syntax

But this does:

>>> f = open(r"c:\python24\image.dat")
>>> line = f.readline()
>>> while line:
...     line = f.readline()
...
>>> f.close()
>>>

Note the differing placement of the f.close() statement, it's not part of
the while.


On 3/22/07, Kent Johnson <kent37 at tds.net> wrote:
>
> Jay Mutter III wrote:
> > Why is it that when I run the following interactively
> >
> > f = open('Patents-1920.txt')
> > line = f.readline()
> > while line:
> >      print line,
> >      line = f.readline()
> > f.close()
> >
> > I get an error message
> >
> > File "<stdin>", line 4
> >      f.close()
> >      ^
> > SyntaxError: invalid syntax
> >
> > but if i run it in a script there is no error?
>
> Can you copy/paste the actual console transcript?
>
> BTW a better way to write this is
> f = open(...)
> for line in f:
>      print line,
> f.close()
>
> Kent
>
> >
> > Thanks
> >
> > Jay
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070322/28b86dee/attachment.htm 


More information about the Tutor mailing list