This is my first program in Python
Steve Holden
sholden at holdenweb.com
Thu Jan 18 08:21:47 EST 2001
"Richard Zilavec" <rzilavec at tcn.net> wrote in message
news:3a66a585.268350144 at news.tcn.net...
>
> I've spent the last few weeks trying to find a good book on Python.
> Seems that most stores don't carry a large selection, however I found
> The Quick Python Book.. The material seems to flow in the right
> direction and the fonts are easy on the eyes.
>
> Anyways, I wrote my first program but was stumped on readline(). I
> could get the first line, but not the rest of the file. I tried
> searching python.org and could not find an example.... well here it
> is:
>
> import string
> file = open("/tmp/globs", 'r')
> for line in file.readlines():
> (first,second) = string.split(line,':',1)
> print first
> file.close()
>
Very Pythonic! The parentheses are unnecessaary in the assignment, but
that's a nit. Also, in Python 2 you could replace string.split(line, ":", 1)
with line.split(':', 1), and avoid the need to import the string module. But
that's another nit. This is a good program.
> This was my first attempt, which looks like it should work but failed:
> invalid syntax. Is this not possible?
> while line = file.readlines():
>
The assignment has deliberately been designated a statement rather than an
expression,
The standard idiom for doing this with a while would be (untested):
while 1:
line = file.readline()
if line == '':
break
first, second = line.split(':', 1)
print first
Some people don't like this. It's not going to change :-)
> Am I using string.split properly?
>
Yes, but strings now have a split() method, so the first argument is
implicit as I mentioned above.
> I was quite happy with how easy this was to put together, I'm just not
> sure if its totally correct.
>
> --
> Richard Zilavec
> rzilavec at tcn.net
>
Totally. Well done!
regards
Steve
More information about the Python-list
mailing list