Python prob

Gerhard Häring gh at ghaering.de
Fri May 30 08:55:39 EDT 2003


Darren Teo wrote:

> Hey just wondering y this does not work .. i am tryin to read from a 
> file and it returns a list of all lines from a file except lines with a 
> '#'. The lines returned also must not end with new-line chars. Can any 
> one help?
> thanx =)
>  
> import string
> import sys
>  
> true = 1
> false = 0
> 
> def readlines(filename):
>    infile = open("test.txt", "r")
>    while 1:
>       text = infile.readlines()
>       if text == "":
>          break
>       if text[0] == '#':
>          continue
>       if not text:
>          break
>       text = text.rstrip()
>       infile.close()
>       return text

readlines() will read the entire file into a list of strings, one list 
item for each line. So what you want here is *readline*, not *readlines*.

Next, do you know about generators/iterators? ;-) If you used readline, 
replaced "return" with "yield" and would not close the file then your 
function would actually work as a generator :-)

Anyway I guess you did not intend to write a generator and just wanted 
the function to return a list of lines that do not start with '#' :-) 
This is a simple approach:

#v+
def filter_file(filename):
     infile = open(filename, "r")
     l = []
     for line in infile:
         if not line.startswith("#"):
             l.append(line.rstrip())
     infile.close()
     return l
#v-

The main difference to your code is that I append to a temporary list 
here, then if finished return the list. I also use for instead of while 
to iterate over the lines in the file because that's just easier.

Here's another approach using readlines() and a list comprehension.

#v+
def filter_file2(filename):
     infile = open(filename, "r")
     lines = infile.readlines()
     infile.close()

     return [line.rstrip() for line in lines if not line.startswith("#")]
#v-

You should be able to look up the methods used (startswith on strings, 
readline and readlines) in the Python documentation if you're not 
familiar with them.

-- Gerhard






More information about the Python-list mailing list