current_class = Classes[student_class] #Used to get the value of the key in Classes
class_score = open(current_class, 'a+') #Scores must be appended and not written to avoid overwriting data
class_format = (name + ' scored ' + str(Score) + '\n') #This is the format in which the text file will save the data as
class_score.write(class_format) #Writing the scores to the text file using the format above
class_read = class_score.read() #For some reason, the scores will not be added to the text file unless I add this text (Using OSX)
我使用此代码将(输入名称)的分数保存到文本文件中。有3个文本文件,根据您所在的类(用户输入类),它将分数保存为1,2或3级。
但是,此过程可重复1000次,如果输入的名称相同,则名称为'可以有1000分。我如何限制它,所以当将分数附加到txt文件时,它只保存3个最近的分数
编辑:我已经开发了一些代码,但仍然不知道如何让它取代最老的代码#39;然而得分。
current_class = Classes[student_class] #Used to get the value of the key in Classes
class_score = open(current_class, 'a+') #Scores must be appended and not written to avoid overwriting data
class_format = (name + ' scored ' + str(Score) + '\n') #This is the format in which the text file will save the data as
class_read = class_score.read()
class_count = class_read.count(name)
while True:
if class_count > 3:
else:
class_score.write(class_format) #Writing the scores to the text file using the format above
break
答案 0 :(得分:1)
如果要将文件限制为仅最后三个分数,则在写入文件之前,将其打开以进行阅读并读取/解析前三个分数。
class_score = open(current_class, 'r')
prev_scores = []
for line in class_score:
prev_scores.append(line)
class_score.close()
class_score = open(current_class, 'w')
for p in prev_scores[1:]:
class_score.write(p)
class_score.write(class_format)