【发布时间】:2015-04-29 11:00:51
【问题描述】:
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? ")
【问题讨论】:
-
看起来
line中没有':',所以当它试图用':'分割它时,结果只有一个元素,你不能分配user和@987654329 @ 因为只有一个元素。 -
在
user, score = line.split(':')之前执行print line并检查是否没有':' -
Julien Spronck,我将如何使用“打印线”?像这样:'print line user, score = line.split('scored')?
-
可以显示输入文件吗?
-
我建议你通读 python 教程 (docs.python.org/2/tutorial)
标签: python file text python-idle