[Tutor] input processing question

Tim Condit Tim Condit <timc@ans.net>
Sun, 26 Mar 2000 20:11:07 +0000 (GMT)


Hello, 

I am having some trouble figuring out how to do something simple in a few
steps: 

+ open a file for reading
+ find the number of lines in the file, to use in a loop
+ process the lines

As an example, I want to find out user information at work, and to do
this, I want to get usernames from /etc/passwd -- it's the first field. 
I'm using Python 1.5.1 on Solaris. The first thing that I got hung up on
was this: 

>>> f = open('/etc/passwd', 'r')
>>> len(f.readlines())  
864
>>> len(f.readlines())
0

Okay, I realize that I'm trying to read the same file twice. How can I get
the number of lines in the file _without_ reading it? Is there a better
approach? 


But that is kind of an aside. I'm really wondering about the tasks listed
above. I have tried several different approaches, with an amazing
consistency. Not a single thing I've tried has worked. :) I have deleted
and redefined f each time, by the way.

>>> import string
>>> f = open('/etc/passwd', 'r')
>>> for i in f.readline():
...     string.split(i, ':')
... 
['r']
['o']
['o']
['t']
['', '']
<snip>

Again, one line, and I'm splitting the output at the character level
rather than at the field separator. Actually, it appears to be doing
something funny at the field separator too, but I'm at a loss. What am I
doing wrong here?

By this point I'm feeling amused (because otherwise I'd be getting
frustrated.) I've tried a few other approaches, that also didn't work. 

Any help would be appreciated.

TIA, 
Tim