将python输出打印到html文件

时间:2017-06-02 20:39:14

标签: html python-3.x

我正在编写一个脚本来将输出打印到html文件。我坚持我的输出格式。以下是我的代码:

def printTohtml(Alist):
    myfile = open('zip_files.html', 'w')
    html =  """<html>
    <head></head>
    <body><p></p>{htmlText}</body>
    </html>"""

    title = "Study - User - zip file -  Last date modified"
    myfile.write(html.format(htmlText = title))
    for newL in Alist:
        for j in newL:
            if j == newL[-1]:
                myfile.write(html.format(htmlText=j))
            else:
                message = j + ', '
                myfile.write(html.format(htmlText = message))
    myfile.close()

Alist =  [['123', 'user1', 'New Compressed (zipped) Folder.zip', '05-24-17'],
['123', 'user2', 'Iam.zip', '05-19-17'], ['abcd', 'Letsee.zip', '05-22-17'],
['Here', 'whichTwo.zip', '06-01-17']]

printTohtml(Alist)

我希望我的输出是这样的:

Study - User - zip file -  Last date modified
123, user1, New Compressed (zipped) Folder.zip, 05-24-17
123, user2, Iam.zip, 05-19-17
abcd, Letsee.zip, 05-22-17
Here, whichTwo.zip, 06-01-17

但是我的代码在我自己的路线上给了我一切。有人可以帮帮我吗?

提前感谢您的帮助!

我的输出:

Study - User - zip file - Last date modified 

123, 

user1, 

New Compressed (zipped) Folder.zip, 

05-24-17 

123, 

user2, 

Iam.zip, 

05-19-17 

abcd, 

Letsee.zip, 

05-22-17 

Here, 

whichTwo.zip, 

06-01-17 

2 个答案:

答案 0 :(得分:0)

你可能想尝试类似的东西。我还没有测试,但这将首先创建字符串,然后将其写入文件。可以更快地避免多次写入,但我不确定python如何在后台处理它。

def printTohtml(Alist):
    myfile = open('zip_files.html', 'w')
    html =  """<html>
    <head></head>
    <body><p></p>{htmlText}</body>
    </html>"""

    title = "Study - User - zip file -  Last date modified"
    Alist = [title] + [", ".join(line) for line in Alist]
    myfile.write(html.format(htmlText = "\n".join(Alist)))

    myfile.close()

Alist =  [['123', 'user1', 'New Compressed (zipped) Folder.zip', '05-24-17'],
['123', 'user2', 'Iam.zip', '05-19-17'], ['abcd', 'Letsee.zip', '05-22-17'],
['Here', 'whichTwo.zip', '06-01-17']]

printTohtml(Alist)

答案 1 :(得分:0)

您的问题是每次在文件中写入一行时都包含html,正文和段落标记。

为什么不连接字符串,用<br>标记分隔行,然后将它们加载到文件中,如下所示:

def printTohtml(Alist):
    myfile = open('zip_files.html', 'w')
    html =  """<html>
    <head></head>
    <body><p>{htmlText}</p></body>
    </html>"""

    complete_string = "Study - User - zip file -  Last date modified"
    for newL in Alist:
        for j in newL:
            if j == newL[-1]:
                complete_string += j + "<br>"
            else:
                message = j + ', '
                complete_string += message + "<br>"
    myfile.write(html.format(htmlText = complete_string))
    myfile.close()

此外,您的模板占位符位于错误的位置,它应位于段落标记之间。