2017-04-20 65 views
0

刚开始学习python。试图了解为什么html代码的内容不会出现在创建的文件中。这只是空白。Python会创建html文件,但不会有任何内容

message = """<html> 
<head></head> 
<body><p>Hello World!</p></body> 
</html>""" 


my_html_file = open("/Users/Negus/Desktop/hello.html", "w") 


my_html_file.write(message) 
+1

你需要使用'my_html_file.close()'关闭文件和写出来变化。 – James

+0

谢谢,现在我可以安心:) – Ksuby

回答

1

您必须关闭文件:

message = """<html> 
<head></head> 
<body><p>Hello World!</p></body> 
</html>""" 


my_html_file = open("/Users/Negus/Desktop/hello.html", "w") 


my_html_file.write(message) 

my_html_file.close() 

或者使用此代码:

with open("/Users/Negus/Desktop/hello.html", "w") as my_html_file: 
    my_html_file.write(message) 
相关问题