2017-10-10 55 views
0

如果你沒趕上它的稱號,這是Python的3.6的Python 3.6 - file.write()不實際編寫

我遇到了一個問題,我能夠寫入一個文件,現在我不能。 瘋狂的事情是,這工作得很好。

我試圖追加我的文件,如果它存在,或寫入一個新的文件,如果它不存在。

main_area_text代表下面

<div id="1131607" align="center" 
style="width:970px;padding:0px;margin:0px;overflow:visible;text- 
align:center"></div> 

以下是我的代碼div標籤文本:

main_area_text = #this is equal to the html text above 
       #I've verified this with a watch during debugging 
       #But this doesn't actually matter, because you can put 
       #anything in here and it still doesn't work 
html_file_path = os.getcwd() + "\\data\\myfile.html" 
if os.path.isfile(html_file_path): 
    print("File exists!") 
    actual_file = open(html_file_path, "a") 
    actual_file.write(main_area_text) 
else: 
    print("File does not exist!") 
    actual_file = open(html_file_path, "w") 
    actual_file.write(main_area_text) 

此前,在它的工作狀態,我可以創建/寫/追加。 html和.txt文件。

注意:如果文件不存在,程序仍然會創建一個新的文件......這只是空的。

我對Python語言有點新鮮,所以我意識到這很可能是我可以忽略簡單的東西。 (這實際上是我編寫這段代碼的原因,只是爲了讓自己熟悉python。)

在此先感謝!

+1

該文件是否在其他地方打開? – toonarmycaptain

+4

我懷疑問題是你沒有關閉你的文件。這就是爲什麼你應該總是使用'with'語句來打開文件。然後他們自動關閉。 –

+0

@toonarmycaptain +1對於一個好問題。這實際上是我加倍,三倍,在來到SO之前檢查的第一件事。有一次,python運行的一個陳舊的實例是保持這個文件打開,但這不是問題的實際來源。 –

回答

4

由於您沒有關閉文件,因此數據不會刷新到磁盤。相反,試試這個:

main_area_text = "stuff" 
html_file_path = os.getcwd() + "\\data\\myfile.html" 
if os.path.isfile(html_file_path): 
    print("File exists!") 
    with open(html_file_path, "a") as f: 
     f.write(main_area_text) 
else: 
    print("File does not exist!") 
    with open(html_file_path, "w") as f: 
     f.write(main_area_text) 

蟒蛇with statement將處理數據刷新到磁盤,並自動關閉數據。處理文件時通常使用with

+0

你是真正的MVP –