problems iterating over a files lines

James Henderson james at logicalprogression.net
Wed Jan 21 11:27:55 EST 2004


On Wednesday 21 January 2004 4:00 pm, Jesse Noller wrote:
> I am a relative newbie to python and I am having issues trying to
> iterate over the lines of a file.
>
> I have a text file - foo.bar inside of this file are lines of text:
>
> x-3411342
> y-1324123
> w-2314121
>
> Each with a trailing \n to designate the end of the line.
>
> I am trying to read this file into python - which is simply in and of
> itself, however:
>
> file = open("foo.bar", "rb")
> while 1:
>     lines = file.open().split('\n'):
>     if not lines:
>            break
>     for lines in lines:
>            key = line
>            get.key(key)
>            results = [key, get.up, get.down]
> file.close()
>
> Appends an extra "blank" line to the list of lines, which causes the
> program to crash - secondly, I've looked at about 20 examples, and all
> of them (including this one) suffer from the problem of looping over
> the lines for the number of lines.
>
> What I want to do is open the contents of the file - read the line and
> set a variable - key, and for each line in the file, I want to do
> something with that key - but only once. So I want to read in a line,
> set to a variable, do something, print, and then do it for the next
> line.

First I take it:

>     lines = file.open().split('\n'):

should have been:

>     lines = file.read().split('\n'):

If you used file.read().splitlines() instead you would avoid the extra blank 
line.

A much better way to iterate line-by-line through the list is simply:

for line in file("foo.bar", "rb"):
    # do something to line

(I'm using the built-in file() function - strictly type - which is the new 
name for open().)

I don't know where your "get" comes from so I can't help you with the rest.

James
-- 
James Henderson, Logical Progression Ltd.
http://www.logicalprogression.net/
http://sourceforge.net/projects/mailmanager/





More information about the Python-list mailing list