2017-04-20 36 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)