Ignoring comments - Parsing input file

Tjabo Kloppenburg tjabo.kloppenburg at unix-ag.org
Sat Oct 12 12:17:38 CEST 2002

On Sat, 12 Oct 2002 09:46:24 +0100 Simon Faulkner <news at titanic.co.uk> wrote:

> I am writing a script which reads it's input from a text file
> What is the easiest way to make it ignore lines that start with # or
> blank lines?

there are several ways. One is using regular expressions:

import re

# re_old = re.compile("^(#.*|)$")
re_ignore = re.compile("^(#.*|\s*)$")  # finds lines with spaces also

for line in file:
  line = line.strip()
  if not re_ignore.search( line ):
    processLine( line )


Another possible way is to use "asdfa".find("#")" and len(line):
in python2.2 interactive mode do a
>>> dir("")   # "" = empty string.
you'll see a list of all methods of string.
now enter:
>>> print "".find.__doc__     # print the in-source docs of find method

Read the text printed on your screen :-)

len(line) finally gives you the number of characters in your line string.
probably you shoud better call len( line.strip() ).


Tjabo Kloppenburg
  --=- In  72.50 Tagen ist Weihnachten! -=--

GnuPG Key is on http://www.home.unix-ag.org/tjabo/kontakt.html
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20021012/1f459d14/attachment.sig>

More information about the Python-list mailing list