Using python in CGI

Sheila King usenet at thinkspot.net
Sun Feb 23 11:54:08 EST 2003


On Sun, 23 Feb 2003 13:40:32 +0000, "p.s" <me at home.com> wrote in
comp.lang.python in article <pan.2003.02.23.13.40.31.512332 at home.com>:

> Hi there,
> i'm trying to port my uni assignment from C to python, but having a few
> problems figuring out some things.
> Firstly, file i/o.
> I want something similar to this pseudo code:
> 
> open file
> while not at eof
> 	read first line
> 	if firstchar on line is not "#"
> 		print line
> 	else
> 		go onto next line

f = open(filename, "r")

while 1:
    line = f.readline()
    if not line:
        break
    if not line.startswith("#"):
        print line[:-1]



Is how I would write your psuedo-code.


Note that print statement automatically adds a "\n" character at the end of
the printed line, and you will also have that from the readline() method,
so you will get two "\n" on each line if you simply print line.

Example:

>>> line = f.readline()
>>> line
'From: "Noone" <user at example.com>\n'
>>> line[:-1]
'From: "Noone" <user at example.com>'
>>>

You might alternatively try this:

>>> import sys
>>> sys.stdout.write(line)
From: "Noone" <case at thinkspot.net>
>>>

In which case you will not need to trim the trailing "\n" character, as the
write() method does not add one, but prints exactly what you pass to it.

Note that the startswith() method for strings is probably not available in
older versions of Python, such as before 2.0, in which case I'd write it
as:

f = open(filename, "r")

while 1:
    line = f.readline()
    if not line:
        break
    if line[0] != "#":
        print line


Hope this helps,


-- 
Sheila King
http://www.thinkspot.net/sheila/
http://www.k12groups.org/




More information about the Python-list mailing list