This is my first program in Python
Richard Zilavec
rzilavec at tcn.net
Thu Jan 18 23:03:04 EST 2001
On Thu, 18 Jan 2001 09:32:27 +0100, "Alex Martelli"
<aleaxit at yahoo.com> wrote:
>"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?
Sorry, it worked as expected, I was just looking for pointers, like
the parentheses.
>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').
I was not aware of readline()... my book does not mention it. I
tested readline() versus readlines(), very true, readlines() creates
an array, however
for line in file.readline():
gets an error
Traceback (innermost last):
File "./python.py", line 6, in ?
first,second = string.split(line,':',1)
ValueError: unpack list of wrong size
When using readlines with a for statement, do all the lines in
/tmp/globs get placed into file.readlines(), or does it loop for each
line read? Hope that makes sense.
--
Richard Zilavec
rzilavec at tcn.net
More information about the Python-list
mailing list