if class_number == 0:
#This will create and open a new text file under the name
#of the class_tag variable.
file = open("Class 0" + ".txt", "a")
#This will write down the user's name and their score
file.write(str(name) + " scored " + str(score))
#This will create a new line for each user
file.write("\n")
#This will close the file.
file.close()
import collections
def new3ElementDeque():
return collections.deque([], 3)
nameTop3 = collections.defaultdict(new3ElementDeque)
with open("Class 0.txt") as f:
for line in f:
user, score = line.split(':')
nameTop3[name].append(score)
我试图让程序只保存用户的最后三个分数,而不是将所有分数保存到文本文件中。
现在看起来像这样:
student scored 3
student scored 8
student scored 0
student scored 4
student scored 10
student scored 3
student scored 0
student scored 4
我希望它是这样的:
student scored 3
student scored 0
student scored 4
但是,IDLE shell声明:
name, score = line.split(':')
ValueError: need more than 1 value to unpack
如何让程序存储用户的最后三个分数并将其保存到文本文件?
输入的名称是:
name = input("What is your name? ")
答案 0 :(得分:0)
没有':'在line
中,所以当它尝试将其拆分为':'时,结果只有一个元素而您无法分配用户和分数,因为只有一个元素。
如果您文件中的所有行都是'等等x',您可以将行user, score = line.split(':')
替换为user, score = line.split(' scored ')
with open("Class 0.txt") as f:
for line in f:
user, score = line.split(' scored ')
nameTop3[user].append(score)