【问题标题】:Issue writing to file问题写入文件
【发布时间】:2018-05-26 10:14:05
【问题描述】:

我在写入 HTML 文件时遇到问题。

我希望能够让我的代码放置我在 HTML 中编写的内容,但我的代码只有在此定义中没有任何 While/If 语句时才会这样做。如果我确实有 Whiles/Ifs,我的 HTML 文件只会变成空白。我不知道为什么会发生这种情况,而且我似乎找不到解决方法。

有什么方法可以在不让我的代码删除文件中的所有内容的情况下使用 Whiles/Ifs,而是让它在其中写入我想要的内容?

def invoice_creator_window():
    global total_cost, total_cost_list, list_of_items, invoice_created

    invoice_created = Toplevel()
    invoice_created.focus_set()
    invoice_created.resizable(width = True, height = False)
    invoice_created.title("Invoice Created")
    invoice_created.geometry("300x300")
    invoice_created.geometry("+400+400")
    invoice_created.configure(bg = "limegreen")
    currentDisplay = 10

    print(total_cost, total_cost_list, list_of_items)

    done = Label(invoice_created, text = "Items have been purchased. Invoice has been created. Please check this program's file location.")
    invoice_created = Button(invoice_created, text = "Done", bg = "white", command = close_window)

    # 
    done.grid(row = 1, column = 1, padx = 7.5, pady = space_between)
    invoice_created.grid(row = 2, column = 1, padx = 7.5, pady = space_between)

    # This section is for the invoice creation with HTML.        
    html_formatting_start = """<!DOCTYPE html>
    <html>
    <head>
    <title>Games R Us - Invoice</title>
    </head>
    <body>


    <style>
    body {background-color: #F7D358;}
    h1   {color: #775A03;}
    p    {color: ; border: 1px solid #775A03; padding: 15px; width: 650px}
    </style>

    <center>
    <h1>Games R Us - Invoice Document</h1>    
    """
    counter = 0
    while len(list_of_items) > 0:
        global html_formatting_mid
        print(counter)
        html_formatting_mid = ("""
        <h3>
        <p>
        <img src="https://steamcdn-a.akamaihd.net/steam/apps/211420/header.jpg?t=1483694369"</img>
        <br>""" + str(list_of_items[counter]) + """<br>
        <i>$""" + str(total_cost_list[counter]) + """ AUD</i>   

        </p>
        </h3>
        """)

        if counter >= len(list_of_items) - 1:
            return
        else:
            counter += 1
    html_formatting_end = """
    <h2>In Total: $""" + str(total_cost) +""" AUD</h2>
    <br>

    <b>Information Grabbed from These Links: </b>
    <a href="https://store.steampowered.com/explore/new/">Steam's New Releases</a> [LIVE] - 
    <a href="https://store.steampowered.com/search/?filter=topsellers">Steam's Top Sellers</a> [LIVE] - 
    <a href="https://www.umart.com.au/Headphones_147C.html">Umart's Headphones</a> [PRE-DOWNLOADED] - 
    <a href="https://www.umart.com.au/Microphones_496C.html">Umart's Microphones</a> [PRE-DOWNLOADED]

    </center>
    </body>
    </html>"""

    invoice_creation = open(invoice_file, "w")

    invoice_creation.write(html_formatting_start)
    invoice_creation.write(html_formatting_mid)
    invoice_creation.write(html_formatting_end)

    invoice_creation.close()

#############################################################################

button_buy = Button(welcome_window, text = "Buy", fg = "white", bg = "goldenrod", font = gui_font_10,
                    command = invoice_creator_window)

注意:“total_cost_list”和“list_of_items”都是列表。 “total_cost”是一个值。不要太担心这些的上下文,但我想澄清一下,以防它们可能会影响任何事情。

【问题讨论】:

  • 我不是 Python 专家,但我认为您不应该使用 return 退出您的 while 循环 - 那不应该是 break 吗?我相信return 会完全退出你的函数。
  • (我认为您可以利用 Jinja 模板:jinja.pocoo.org 而不是在变量中处理长 html 字符串)
  • 我建议你写一个人们最终可以运行的最小(非)工作示例,看看问题到底出在哪里。
  • 当你说出来空白时,这是在浏览器中还是在html源中?
  • 这很难阅读,因此很难调试。尝试对其进行重构以提高可读性,错误可能会变得很容易发现。

标签: python html python-3.x tkinter


【解决方案1】:

这是一个尽可能简单的容器中的固定版本代码。

from tkinter import *
import webbrowser
root = Tk ()

space_between, invoice_file = 5, "Invoice.html"
total_cost, total_cost_list, list_of_items = 10, [1, 9], ["Something", "Something 2"]

def close_window (): root.destroy ()

def invoice_creator_window():
    global total_cost, total_cost_list, list_of_items, invoice_created

    invoice_created = Toplevel()
    invoice_created.focus_set()
    invoice_created.resizable(width = True, height = False)
    invoice_created.title("Invoice Created")
    invoice_created.geometry("300x300")
    invoice_created.geometry("+400+400")
    invoice_created.configure(bg = "limegreen")
    currentDisplay = 10

    print(total_cost, total_cost_list, list_of_items)

    done = Label(invoice_created, text = "Items have been purchased. Invoice has been created.")
    invoice_created = Button(invoice_created, text = "Done", bg = "white", command = close_window)

    # 
    done.grid(row = 1, column = 1, padx = 7.5, pady = space_between)
    invoice_created.grid(row = 2, column = 1, padx = 7.5, pady = space_between)

    # This section is for the invoice creation with HTML.        
    html_formatting_start = """<!DOCTYPE html>
    <html>
    <head>
    <title>Games R Us - Invoice</title>
    </head>
    <body>


    <style>
    body {background-color: #F7D358;}
    h1   {color: #775A03;}
    p    {color: ; border: 1px solid #775A03; padding: 15px; width: 650px}
    </style>

    <center>
    <h1>Games R Us - Invoice Document</h1>    
    """
    counter = 0
    html_formatting_mid = ""
    while len(list_of_items) > 0:
        print(counter)
        html_formatting_mid += """
        <h3>
        <p>
        <img src="https://steamcdn-a.akamaihd.net/steam/apps/211420/header.jpg?t=1483694369"</img>
        <br>""" + str(list_of_items[counter]) + """<br>
        <i>$""" + str(total_cost_list[counter]) + """ AUD</i>   

        </p>
        </h3>
        """

        if counter >= len(list_of_items) - 1:
            break
        else:
            counter += 1
    html_formatting_end = """
    <h2>In Total: $""" + str(total_cost) +""" AUD</h2>
    <br>

    <b>Information Grabbed from These Links: </b>
    <a href="https://store.steampowered.com/explore/new/">Steam's New Releases</a> [LIVE] - 
    <a href="https://store.steampowered.com/search/?filter=topsellers">Steam's Top Sellers</a> [LIVE] - 
    <a href="https://www.umart.com.au/Headphones_147C.html">Umart's Headphones</a> [PRE-DOWNLOADED] - 
    <a href="https://www.umart.com.au/Microphones_496C.html">Umart's Microphones</a> [PRE-DOWNLOADED]

    </center>
    </body>
    </html>"""

    invoice_creation = open(invoice_file, "w")

    invoice_creation.write (html_formatting_start + html_formatting_mid + html_formatting_end)

    invoice_creation.close ()

    webbrowser.open (invoice_file)

#############################################################################

button_buy = Button(root, text = "Buy", fg = "white", bg = "goldenrod",
                    command = invoice_creator_window).pack ()
root.mainloop ()

【讨论】:

  • 我刚试了一下,很遗憾,好像没有用。我仍然得到相同的错误,它使 html 文件为空白。
  • 你使用的是什么操作系统?
  • 尝试更新后的代码(因为它在保存之前连接了 HTML 代码)
  • 我使用的是 Windows 10,但即使在此之后问题仍然存在。
【解决方案2】:

我找到了解决办法。

def invoice_creator_window():
    global total_cost, total_cost_list, list_of_items, invoice_created

    invoice_created = Toplevel()
    invoice_created.focus_set()
    invoice_created.resizable(width = True, height = False)
    invoice_created.title("Invoice Created")
    invoice_created.geometry("300x300")
    invoice_created.geometry("+400+400")
    invoice_created.configure(bg = "limegreen")
    currentDisplay = 10

    print(total_cost, total_cost_list, list_of_items)

    done = Label(invoice_created, text = "Items have been purchased. Invoice has been created. Please check this program's file location.")
    invoice_created = Button(invoice_created, text = "Done", bg = "white", command = close_window)

    # 
    done.grid(row = 1, column = 1, padx = 7.5, pady = space_between)
    invoice_created.grid(row = 2, column = 1, padx = 7.5, pady = space_between)

    # This section is for the invoice creation with HTML.        
    html_formatting_start = """<!DOCTYPE html>
    <html>
    <head>
    <title>Games R Us - Invoice</title>
    </head>
    <body>


    <style>
    body {background-color: #F7D358;}
    h1   {color: #775A03;}
    p    {color: ; border: 1px solid #775A03; padding: 15px; width: 650px}
    </style>

    <center>
    <h1>Games R Us - Invoice Document</h1>    
    """
    counter = 0
    html_formatting_mid = ""
    for items in list_of_items:
        print(counter)
        html_formatting_mid += ("""
        <h3>
        <p>
        <img src="https://steamcdn-a.akamaihd.net/steam/apps/211420/header.jpg?t=1483694369"</img>
        <br>""" + str(list_of_items[counter]) + """<br>
        <i>$""" + str(total_cost_list[counter]) + """ AUD</i>   

        </p>
        </h3>
        """)
        counter += 1
    html_formatting_end = """
    <h2>In Total: $""" + str(total_cost) +""" AUD</h2>
    <br>

    <b>Information Grabbed from These Links: </b>
    <a href="https://store.steampowered.com/explore/new/">Steam's New Releases</a> [LIVE] - 
    <a href="https://store.steampowered.com/search/?filter=topsellers">Steam's Top Sellers</a> [LIVE] - 
    <a href="https://www.umart.com.au/Headphones_147C.html">Umart's Headphones</a> [PRE-DOWNLOADED] - 
    <a href="https://www.umart.com.au/Microphones_496C.html">Umart's Microphones</a> [PRE-DOWNLOADED]

    </center>
    </body>
    </html>"""

    invoice_creation = open(invoice_file, "w")

    invoice_creation.write(html_formatting_start)
    invoice_creation.write(html_formatting_mid)
    invoice_creation.write(html_formatting_end)

    invoice_creation.close()

#############################################################################

button_buy = Button(welcome_window, text = "Buy", fg = "white", bg = "goldenrod", font = gui_font_10,
                    command = invoice_creator_window)

我回到了我以前使用的 for 循环并尝试使用它。除了这一次,我添加了 html_formatting_mid += (""" 到它,然后在 for 循环之前添加了 html_formatting_mid = "",就像 Minion Jim 展示的那样。

现在完全可以使用了。

【讨论】:

    【解决方案3】:

    简短的回答是,您可以在附加模式下编写。 open (filename, 'a') 而不是 open (filename, 'w')。这将添加到文件中已有的任何内容,因此您可能需要先截断它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-07
      • 2016-08-15
      • 2011-09-15
      相关资源
      最近更新 更多