Ignoring comments - Parsing input file

Erik Max Francis max at alcyone.com
Sat Oct 12 11:23:25 CEST 2002


Simon Faulkner 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?

Something like:

	while 1:
	    line = input.readline()
	    if not line:
	        break
	    if line[-1] == '\n':
	        line = line[:-1] # strip newline
	    if line.find('#') >= 0):
	        line = line.split('#', 1)[0] # remove everything
	    if not line:
	        continue # skip blank lines

If your lines are insensitive to whitespace, a line = line.strip() would
be in order there too.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ When angry, count four; when very angry, swear.
\__/ Mark Twain
    Polly Wanna Cracka? / http://www.pollywannacracka.com/
 The Internet resource for interracial relationships.



More information about the Python-list mailing list