2017-02-12 31 views
1

当我键入下面的代码时,它给了我一个空白的HTML页面。即使我把<h1><a href>标签。只有<title>标签被执行。有谁知道为什么以及如何解决它?python文件中的HTML字符串没有按预期执行

代码:

my_variable = ''' 
      <html> 
       <head> 
        <title>My HTML File</title> 
       </head> 
       <body> 
        <h1>Hello world!</h1> 
        <a href="https://www.hipstercode.com" target = "_blank">Click me</a> 
       </body> 
      </html>''' 

my_html_file = open(r"\Users\hp\Desktop\Code\Python testing\CH\my_html_file.html", "w") 

my_html_file.write(my_variable) 

提前感谢!

+1

这可能是因为你没有正确关闭文件。尝试'打开(...)为my_html_file:my_html_file.write(my_variable)'。 –

+0

它适用于我。请注意,我为html文件使用了不同的名称。我看到标题,h1标题和链接。 –

+0

你是如何打开html文件的? –

回答

0

正如@bill Bell所说,这可能是因为你没有关闭你的文件(所以它没有刷新它的缓冲区)。

所以,你的情况:

my_html_file = open(r"\Users\hp\Desktop\Code\Python testing\CH\my_html_file.html", "w") 
my_html_file.write(my_variable) 
my_html_file.close() 

但是,这不是做的正确方法。事实上,如果第二行发生错误,文件将永远不会关闭。因此,您可以使用with声明确保它始终。 (就像@Rawing说)

with open('my-file.txt', 'w') as my_file: 
    my_file.write('hello world!') 

所以,其实,这就像如果你这样做:

my_file = open('my-file.txt', 'w') 
try: 
    my_file.write('hello world!') 
finally: 
    # this part is always executed, whatever happens in the try block 
    # (a return, an exception) 
    my_file.close() 
相关问题