Need help removing list elements.

nuffnough at gmail.com nuffnough at gmail.com
Sat Apr 29 09:08:10 EDT 2006


This is python 2.4.3 on WinXP under PythonWin.

I have a config file with many blank lines and many other lines that I
don't need.

read the file in,  splitlines to make a list, then run a loop that
looks like this:



config_file = open("lines.txt", "rb")
returned_lines = config_file.read().splitlines()

i = len(returned_lines)


for i in range(i):
    if returned_lines[i].find("Value") == -1:
        if returned_lines[i].find("Name") == -1:
            print "read in this useless line ..."
            print returned_lines[i]
            print "Removing line ..."
            returned_lines[i] = ""




This blanks out all the lines I don't want.  I did originally try 'del
returned_lines[i]' but I got list index out of range, so I made a loop
to delete the empty elements.

for i in range(i):
    if returned_lines[i] == "":

        del returned_lines[i]



But this gives me "IndexError: list out of range

After much experimentation and dumping of the list, I have figured out
that it doesn't like removing multiple empty elements in a row.  In
other words, if there are 4 empty lines,  it will remove one of them,
and seems to behave as though that was one element instead of 3.  if I
make i = i - *number of groups of empty elements* it works without an
error,  but leaves many empty elements behind.

Obviously I can iterate over it time and again,  but that isn't how the
world should work.

Is this something obvious that I am doing wrong, or something more
complicated?

Any help will be gratefully appreciated!




More information about the Python-list mailing list