2017-06-02 97 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() 

此外,模板佔位符是在錯誤的地方,它應該在你的段落標籤之間。