This is my first program in Python

Alex Martelli aleaxit at yahoo.com
Thu Jan 18 03:32:27 EST 2001


"Richard Zilavec" <rzilavec at tcn.net> wrote in message
news:3a66a585.268350144 at news.tcn.net...
    [snip]
> import string
> file = open("/tmp/globs", 'r')
> for line in file.readlines():
>         (first,second) = string.split(line,':',1)
>         print first
> file.close()

Looks fine to me -- you can omit the parentheses around first, second in
the loop body's first line, but it should accept them if you insist on
using them.  What problem is this giving you?


> This was my first attempt, which looks like it should work but failed:
> invalid syntax.  Is this not possible?
> while line = file.readlines():

No, because assignment is a statement, and the while condition is
an expression.  This question is frequently asked, because of other
languages (C, Perl, etc) where assignment is an operator, quite
acceptable inside any expression; Python takes a different tack
(partly to eliminate possibility of errors due to = vs == confusion).

In this specific case, please note that .readlines() returns ALL
of the lines in the file as one list, so, even with assignment
inside expression, this would not work; you probably want to use
.readline() [NO trailing s], which, each time it's called, returns
the 'next' line ('' when there are no more lines -- and this is
the only result from .readline() that will test as 'false', since
all other lines have, at least, their ending '\n', and non-empty
strings test as 'true').


If you must translate some code using assignment-inside-expression
to Python and want to keep close to the original code's structure,
a viable workaround may be:

class Data:
    def set(self, data):
        self.data = data
        return self.data

and then you can do (although probably unwarranted in this case):

line = Data()
while line.set(file.readline()):
    first, second = string.split(line.data,':',1)
    print first


Alex






More information about the Python-list mailing list