我试图做一个程序,它将询问用户的名字,然后一系列的问题。每答对一次加分。我试图让它把分数和用户名一起存储到一个文本文件中,这样它在文本文件上看起来是这样的:
Name Score
以John为例,如果他得4分,在文本文件中会写下:
^{pr2}$但我希望这样,如果约翰再参加一次考试,而不是让约翰参加两次考试:
John 4
John 6
我想把它改成:
John 4 6
它不会重写名字和分数,而是将tab和分数写在与John名字相同的行上。在
以下是我目前为止的代码:
import random
name = input("Hello user, what is your name?")
count = (0)
score = (0)
while count != (8):
count = count + (1)
symbols = ['+', '-', '*']
valueF = random.randint(1,10)
valueS = random.randint(1,10)
chosensymb = random.choice (symbols)
question = input("What is %d %s %d ? :"%(valueF, chosensymb, valueS))
answer = eval(str(valueF) + chosensymb + str(valueS))
if question == str(answer):
score = score + (1)
print ("Correct")
else:
print ("Incorrect")
print("%s, you have scored %d points"%(name,score))
filewrite = open("ScoreSheet.txt","a")
filewrite.write("\n%s\t%d"%(name,score))
filewrite.close()
我不知道怎么做,我是python新手,如果我犯了什么错误,很抱歉,谢谢!在
文件访问不是这样工作的:在文件中,您不能只在某个地方“插入”新值,将文件的其余部分向后移动;您只能覆盖字符或重写整个文件。在
一般来说,只要你的文件很短,你不会注意到任何性能影响,如果重写整个文件。在
首先,你可以把每个人的分数都储存在字典里。 让我们介绍一个
scores
对象:它将名称作为键,分数作为值。像这样:
^{pr2}$如果您引入了一个新的播放器,我们将在该字典中创建一个新元素,我们将其命名为
'John'
,分数为0
:如果玩家猜对了,我们会增加玩家的分数:
(如果只想在对象中添加一些内容,可以使用
+=
运算符。这是一种简短的说法。在然后魔法开始了!
Python中有一个内置模块,名为
pickle
,它可以将对象(比如我们制作的字典-scores
)存储在文件中,然后将它们从文件中弹出,然后将它们还原!在这里有a quick manual关于如何使用
pickle
。简而言之,您可以这样将分数保存到文件中:然后像这样加载:
这并不是存储信息的最佳方式—还有更多类似json,csv,sqlite的东西,甚至还有手动读/写功能,但你现在还可以:)
只需使用^{} 或^{} 对数据进行serialize。下面是一个使用} -名称和分数之间的映射):
json
序列化分数的示例(将分数存储在^{现在我们将创建一个函数,将分数写入给定文件:
^{pr2}$它的作用是:
dict
)dict
(add key/update value of key)在编写
write_score
函数时,我们缺少了一个read_scores
函数,它使我们能够看到当前的分数。我们写下这个read_scores
:read_scores
的作用是:dict
(使用^{现在我们可以测试它是否真的有效。下面是一个小例子:
技巧1:在写分数时,您可能需要使用^{} ,这样}被视为同一个用户。在
john
和{技巧2:因为我们将
json
库作为serializer
引用,并且它与pickle
具有相同的API,您可以通过将import json as serializer
替换为import pickle as serializer
在这两者之间进行选择。只需确保删除分数文件,因为它们不会以相同的方式序列化数据。在将整个代码放在一起:
输出:
要读取特定分数,可以使用现有方法
read_scores
:奖金-Closures:
如果您了解闭包,可以使用以下方法使函数特定于文件:
现在,我们只需调用带有file name参数的函数一次,从那时起,我们就可以使用结果来写分数:
对
read_score
也做了同样的处理:包含闭包的整个代码:
输出:
相关问题 更多 >
编程相关推荐