Python cgi script

Christopher T King squirrel at WPI.EDU
Thu Aug 5 18:44:02 CEST 2004

On Thu, 5 Aug 2004, Yong Wang wrote:

> file=open('/apps/www/htdocs/internal/nd/output1', 'r')
> flag=0
> while not flag
>     aLine = file.readline()
>     if aLine != "":
>         print aLine
>         print '\n'
>     else:
>         flag = 1
> file.close()
> print "</body>"
> print "</html>" 

> The output from print statement above in web can display, but no line
> separation between different lines. How can I preserve the orginal line
> format of the input file (space within a line and space between lines)?

HTML generally ignores whitespace.  You need to either append a break tag 
(<br/>) to each line, or enclose the output in <pre>...</pre>.  Also don't 
forget to start the document with <html><body>.

A couple of other notes:

file.readline() retains the line's newline terminator, and print adds one.  
Your code ends up printing 4 newlines per actual line.  Just using
'print aLine,' should work (the trailing comma prevents print from adding 
a newline).

Assuming you are using a relatively recent version of Python (2.2 or 2.3, 
not sure about 2.1), you can rewrite your loop using iteration over the 
file object:

 for aLine in file:
     print aLine,

More information about the Python-list mailing list