2017-06-02 56 views
1

我正在写一个脚本来打印输出到一个html文件。我困在我的输出格式。下面是我的代码:打印python输出到一个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 

回答

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) 
0

您的问题是,每当您向文件写入一行时,都会包含html,body和paragraph标记。

你为什么不串连你的字符串,分离与<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() 

此外,模板占位符是在错误的地方,它应该在你的段落标签之间。