Using python in CGI

Sheila King usenet at thinkspot.net
Sun Feb 23 11:40:36 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
> 
> The python docs only discuss file.readline/s() in any depth, but I'd like
> some details on how to read the first char from a line, and also the first
> string from a line.

I'm not sure why you want to read only one char at a time, but...
the Python docs do tell how to do that right here:
http://www.python.org/doc/current/lib/bltin-file-objects.html#l2h-164

Example:

>>> f = open("article.txt", "r")
>>> f.read(1)
'F'
>>> f.read(1)
'r'
>>> f.read(1)
'o'
>>> f.read(1)
'm'
>>> f.read(1)
':'
>>> f.read(1)
' '

and so on.

I'm not sure what you mean by "The first string from a line"? Do you 
mean up until the first white space is encountered? That isn't so easy to
do.

I would instead suggest something like this:

>>> f.close()
>>> f = open("article.txt", "r")
>>> line = f.readline()
>>> line
'From: "Noone" <user at example.com>\n'
>>> tokens = line.split()
>>> tokens
['From:', '"Noone"', '<user at example.com>']
>>> firststring = tokens[0]
>>> firststring
'From:'
>>> for token in tokens:
...     print "Next string: %s" % token
...
Next string: From:
Next string: "Noone"
Next string: <user at example.com>



> I'm also interested in any information about directly outputting text from
> a file, onto the page(web browser).  Both raw( with "\n" and "\t" etc),
> and ascii (just a-z, A-Z, and 0-9).

CGI just prints whatever you output to the browser. I'm not sure what
you're distinction is between "raw" and ASCII.

In general:

>>> f = open(filename, "w")
>>> f.write()

Would output the contents of the file to the browser in a CGI script.


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




More information about the Python-list mailing list