2017-03-06 77 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() 

固定它

相关问题