Python prob

Roy Smith roy at panix.com
Fri May 30 09:12:04 EDT 2003


In article <mailman.1054298446.21505.python-list at python.org>,
 Darren Teo <darrenteo82 at yahoo.com> 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

The most obvious thing is that you call infile.readlines() [not to 
mention infile.close()] inside your loop.  You probably want to start 
with something like:

infile = open("test.txt", "r")
nonCommentLines = []
for text in infile.readlines():
   if line is ok to use...  # pseudocode
      nonCommentLines.append (text.rstrip())
infile.close()

Note that rstrip() gets rid of all whitespace at the end of the string.  
You said you only wanted to strip the newlines.  The way it's written 
above, it'll also strip any spaces that may be at the end of the line 
before the newline.  This may or may not be what you want.  I suggest 
looking at the endswith() string method and the string slicing operator.

As a stylistic point, I'd also suggest naming your function something 
other than readlines.  Although the Python name scoping system makes it 
possible to have two different functions with the same name, it's 
probably just added confusion you don't need right now.  Name your 
function getNonCommentLines or something like that.




More information about the Python-list mailing list