Search code examples
pythonhtmlfile-iocherrypy

With python and cherrypy, how do i read a txt file and display it to a page?


I have got a txt file in the format of:

line_1
line_2
line_3

I am trying to read it into a list and displaying it on to a web page just as it looks inside the txt file; one line under another. Here is my code

@cherrypy.expose
def readStatus(self):

    f = open("directory","r")
    lines = "\n".join(f.readlines())
    f.close()
    page += "<p>%s</p>" % (lines)

However, the output i have been getting is:

line_1 line_2 line_3

It would be great if someone could give me a hit as to what to do so line_1, line_2 and line_3 are displayed on 3 seperate lines inside the web browser?

Thanks in advance.


Solution

  • You're wrapping paragraph tags around all of the filenames. You probably meant to put paragraph tags around each filename individually:

    with open("directory", "r") as f:
        page = "\n".join("<p>%s</p>" % line for line in f)
    

    Or, more semantically, you could put it all in an unordered list:

    with open("directory", "r") as f:
        page = '<ul>%s</ul>' % "\n".join("<li>%s</li>" % line for line in f)
    

    Alternatively, you could put it all inside of a pre (preformatted text) tag:

    with open('directory', 'r') as f:
        page = '<pre>%s</pre>' % f.read()
    

    Additionally, you might want to consider escaping the filenames with cgi.escape so browsers don't interpret any special characters in the filename.