2017-03-06 30 views
0

這部分代碼應該將輸入和另一個變量(Score)寫入文本文件。程序要求輸入(所以if語句肯定工作)並且運行沒有錯誤,但是文本文件是空的。奇怪的是,將這段代碼複製到一個空的python文件並運行它沒有任何錯誤。這裏發生了什麼?Python:嘗試附加到文件,但沒有任何內容正在寫入

if Score > int(HighScores[1]): 
    print("You beat the record with " + str(Score) + " points!") 
    Name = input("What is your name?") 
    BestOf = open("High Scores.txt", "w").close() 
    BestOf = open("High Scores.txt", "a") 
    BestOf.write(Name + "\n") 
    BestOf.write(str(Score)) 
+2

你肯定要追加後關閉文件? –

+3

此外,你會意識到'BestOf = open(「High Scores.txt」,「w」)。close()簡單地截斷文件,本質上刪除已經存在的任何內容?因此它沒有任何意義,並且你可以在整個時間使用'open(...,'w')',因爲*沒有任何可以追加到*的地方。 –

+0

Idk如果你需要先寫這個,但是我認爲'open(「High Scores.txt」,「w」)'會覆蓋以前的內容,因爲你沒有以追加模式打開它。 – Carcigenicate

回答

0

嘗試以'w +'模式打開文件。這將創建文件,如果它不存在。 您也可以使用'os'模塊檢查文件是否退出。

import os; 
if Score > int(HighScores[1]): 
    print("You beat the record with " + str(Score) + " points!") 
    name = input("What is your name?") 
    if os.path.isfile("Scores.txt"): 
     fh = open("Scores.txt", "a") 
    else: 
     fh = open("Scores.txt", "w+") 
    fh.write(name + "\n") 
    fh.write(str(Score)) 
    fh.close() 
1

我追加後沒有關閉文件。

BestOf.close() 

固定它

相關問題