Python 用户分数保存程序

Python 用户分数保存程序,python,Python,我正在尝试制作一个程序,它将询问用户的姓名,然后询问一系列问题。每次问题正确时加一分。我试图让它将分数和用户名一起存储到文本文件中,以便在文本文件中看起来像这样: Name Score 让我们以John为例,如果他得到4分,那么在文本文件中会写: John 4 但我希望这样,如果约翰再次参加考试,而不是让约翰参加两次考试: John 4 John 6 我希望它是这样的: John 4 6 它不需要重写名字和分数,而是将tab和分数写在同一行上,与名字为

我正在尝试制作一个程序,它将询问用户的姓名,然后询问一系列问题。每次问题正确时加一分。我试图让它将分数和用户名一起存储到文本文件中,以便在文本文件中看起来像这样:

Name    Score 
让我们以John为例,如果他得到4分,那么在文本文件中会写:

John    4
但我希望这样,如果约翰再次参加考试,而不是让约翰参加两次考试:

John    4
John    6
我希望它是这样的:

John    4   6
它不需要重写名字和分数,而是将tab和分数写在同一行上,与名字为johnin的那一行相同

以下是我目前的代码:

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
对象:

scores = {}
它将以名称作为键,分数作为值。就像这样:

scores = {'John': 2,
          'Mary': 5}
如果你介绍了一个新玩家,我们将在所述词典中创建一个新元素,我们称之为
'John'
,分数为
0

scores['John'] = 0
如果玩家猜对了,我们会增加玩家的分数:

scores['John'] += 1
(如果您只想向对象添加一些内容,可以使用
+=
运算符。这是表示
分数['John']]=scores['John']+1的较短方式

然后魔术开始了!
Python中有一个内置模块,名为
pickle
,它可以将对象(如我们制作的字典-
分数
)存储在文件中,然后将它们从文件中弹出,并将其还原

关于如何使用
pickle
,有一些详细的说明。简言之,您可以这样将分数保存到文件中:

import pickle
pickle.dump(scores, open("scores.p", "wb"))
scores = pickle.load(open("scores.p", "rb"))
然后像这样加载它:

import pickle
pickle.dump(scores, open("scores.p", "wb"))
scores = pickle.load(open("scores.p", "rb"))

这并不是最好的存储东西的方法——还有更多类似的东西,甚至是手动读/写,但现在你还可以:)

首先,你可以将每个人的分数存储在字典中。 让我们介绍一个
scores
对象:

scores = {}
它将以名称作为键,分数作为值。就像这样:

scores = {'John': 2,
          'Mary': 5}
如果你介绍了一个新玩家,我们将在所述词典中创建一个新元素,我们称之为
'John'
,分数为
0

scores['John'] = 0
如果玩家猜对了,我们会增加玩家的分数:

scores['John'] += 1
(如果您只想向对象添加一些内容,可以使用
+=
运算符。这是表示
分数['John']]=scores['John']+1的较短方式

然后魔术开始了!
Python中有一个内置模块,名为
pickle
,它可以将对象(如我们制作的字典-
分数
)存储在文件中,然后将它们从文件中弹出,并将其还原

关于如何使用
pickle
,有一些详细的说明。简言之,您可以这样将分数保存到文件中:

import pickle
pickle.dump(scores, open("scores.p", "wb"))
scores = pickle.load(open("scores.p", "rb"))
然后像这样加载它:

import pickle
pickle.dump(scores, open("scores.p", "wb"))
scores = pickle.load(open("scores.p", "rb"))
这并不是最好的存储方式——还有更多类似的东西,甚至是手动读/写,但你现在还可以:)

只需要使用或来存储数据。下面是一个使用
json
序列化分数的示例(将分数存储在名称和分数之间的-a映射中):

现在,我们将创建一个函数,将分数写入给定文件:

def write_score(score_file_name, name, score):
    scores = read_scores(score_file_name)
    # add score
    scores[name] = score
    with open(score_file_name, 'w') as f:
        serializer.dump(scores, f)
它所做的是:

  • 从score文件加载序列化结果对象(
    dict
  • 更新分数
    dict
    (添加键/更新键的值)
  • 将更新的
    dict
    写入文件(使用)
  • 在编写
    write_score
    函数时,我们缺少一个
    read_scores
    函数,该函数使我们能够查看当前的分数。那么,让我们来写这个
    阅读分数

    def read_scores(score_file_name):
        try:
            with open(score_file_name, 'r') as f:
                scores = serializer.load(f)
            return scores
        except IOError:
            # if file does not exist - we have no scores
            return {}
    
    def read_score(score_file_name, name):
        return read_scores(score_file_name)[name]
    
    read_scores
    所做的是:

  • 读取序列化的
    dict
    (使用)
  • 现在我们可以测试它是否真的有效。下面是一个小例子:

    # set the score file name
    SCORES_FILE_NAME = 'scores.txt'
    
    write_score(SCORES_FILE_NAME, 'john', 10)    
    print(read_scores(SCORES_FILE_NAME))
    
    write_score(SCORES_FILE_NAME, 'jim', 11)    
    print(read_scores(SCORES_FILE_NAME))
    
    # overwrite john's score
    write_score(SCORES_FILE_NAME, 'john', 12)
    print(read_scores(SCORES_FILE_NAME))
    
    技巧1:您可能希望在编写分数时使用,以便将
    john
    john
    视为同一用户

    技巧2:因为我们将
    json
    库引用为
    serializer
    ,并且它具有与
    pickle
    相同的API,所以您只需将
    import json as serializer
    替换为
    import pickle as serializer
    ,即可在两者之间进行选择只需确保删除分数文件,因为它们不会以相同的方式序列化数据

    将整个代码放在一起:

    # import the serializing library
    import json as serializer
    
    def write_score(score_file_name, name, score):
        scores = read_scores(score_file_name)
        # add score
        scores[name] = score
        with open(score_file_name, 'w') as f:
            serializer.dump(scores, f)
    
    
    def read_scores(score_file_name):
        try:
            with open(score_file_name, 'r') as f:
                scores = serializer.load(f)
            return scores
        except IOError:
            # if file does not exist - we have no scores
            return {}
    
    # TESTS
    
    # set the score file name
    SCORES_FILE_NAME = 'scores.txt'
    
    write_score(SCORES_FILE_NAME, 'john', 10)
    print(read_scores(SCORES_FILE_NAME))
    
    write_score(SCORES_FILE_NAME, 'jim', 11)
    print(read_scores(SCORES_FILE_NAME))
    
    # overwrite john's score
    write_score(SCORES_FILE_NAME, 'john', 12)
    print(read_scores(SCORES_FILE_NAME))
    
    # import the library
    import serializer
    
    # CLOSURES
    
    SCORES_FILE = 'scores.txt'
    def read_scores(score_file_name):
        # create closure function
        def read_scores_specific():
            try:
                with open(score_file_name, 'r') as f:
                    scores = serializer.load(f)
                return scores
            except IOError:
                # if file does not exist - we have no scores
                return {}
        return read_scores_specific
    
    def write_score(score_file_name):
        # create closure specific to 'score_file_name'
        def write_score_specific(name, score):
            scores_reader = read_scores(score_file_name)
            scores = scores_reader()
            # add score
            scores[name] = score
            with open(score_file_name, 'w') as f:
                serializer.dump(scores, f)
    
        # return file-specific function
        return write_score_specific
    
    # create specific 'write_score' for our file
    score_txt_writer = write_score(SCORES_FILE)
    
    # update john's score to 10 without specifying the file
    score_txt_writer('john', 10)
    
    
    score_txt_reader = read_scores(SCORES_FILE)
    
    print score_txt_reader()
    
    输出:

    {u'john': 10}
    {u'john': 10, u'jim': 11}
    {u'jim': 11, u'john': 12}
    
    {u'john': 10}
    
    要读取特定分数,您可以使用现有方法读取分数

    def read_scores(score_file_name):
        try:
            with open(score_file_name, 'r') as f:
                scores = serializer.load(f)
            return scores
        except IOError:
            # if file does not exist - we have no scores
            return {}
    
    def read_score(score_file_name, name):
        return read_scores(score_file_name)[name]
    
    奖金-: 如果您了解闭包,可以通过以下方式使函数特定于文件:

    def write_score(score_file_name):
        # create closure specific to 'score_file_name'
        def write_score_specific(name, score):
            scores = read_scores(score_file_name)
            # we're going to make a 'read_scores' with closures as well!
            # so use that one...
            scores_reader = read_scores(score_file_name)
            scores = scores_reader()
    
    
            # add score
            scores[name] = score
            with open(score_file_name, 'w') as f:
                serializer.dump(scores, f)
    
        # return file-specific function
        return write_score_specific
    
    现在,我们只需使用file name参数调用函数一次,从那一刻起,我们就可以使用write scores的结果:

    # create specific 'write_score' for our file
    score_txt_writer = write_score('scores.txt')
    
    # update john's score to 10 without specifying the file
    score_txt_writer('john', 10)
    
    同样的方法也适用于
    读取分数

    def read_scores(score_file_name):
        # create closure function
        def read_scores_specific():
            try:
                with open(score_file_name, 'r') as f:
                    scores = serializer.load(f)
                return scores
            except IOError:
                # if file does not exist - we have no scores
                return {}
        return read_scores_specific
    
    包含闭包的整个代码:

    # import the serializing library
    import json as serializer
    
    def write_score(score_file_name, name, score):
        scores = read_scores(score_file_name)
        # add score
        scores[name] = score
        with open(score_file_name, 'w') as f:
            serializer.dump(scores, f)
    
    
    def read_scores(score_file_name):
        try:
            with open(score_file_name, 'r') as f:
                scores = serializer.load(f)
            return scores
        except IOError:
            # if file does not exist - we have no scores
            return {}
    
    # TESTS
    
    # set the score file name
    SCORES_FILE_NAME = 'scores.txt'
    
    write_score(SCORES_FILE_NAME, 'john', 10)
    print(read_scores(SCORES_FILE_NAME))
    
    write_score(SCORES_FILE_NAME, 'jim', 11)
    print(read_scores(SCORES_FILE_NAME))
    
    # overwrite john's score
    write_score(SCORES_FILE_NAME, 'john', 12)
    print(read_scores(SCORES_FILE_NAME))
    
    # import the library
    import serializer
    
    # CLOSURES
    
    SCORES_FILE = 'scores.txt'
    def read_scores(score_file_name):
        # create closure function
        def read_scores_specific():
            try:
                with open(score_file_name, 'r') as f:
                    scores = serializer.load(f)
                return scores
            except IOError:
                # if file does not exist - we have no scores
                return {}
        return read_scores_specific
    
    def write_score(score_file_name):
        # create closure specific to 'score_file_name'
        def write_score_specific(name, score):
            scores_reader = read_scores(score_file_name)
            scores = scores_reader()
            # add score
            scores[name] = score
            with open(score_file_name, 'w') as f:
                serializer.dump(scores, f)
    
        # return file-specific function
        return write_score_specific
    
    # create specific 'write_score' for our file
    score_txt_writer = write_score(SCORES_FILE)
    
    # update john's score to 10 without specifying the file
    score_txt_writer('john', 10)
    
    
    score_txt_reader = read_scores(SCORES_FILE)
    
    print score_txt_reader()
    
    输出:

    {u'john': 10}
    {u'john': 10, u'jim': 11}
    {u'jim': 11, u'john': 12}
    
    {u'john': 10}
    
    只需使用或编辑您的数据。下面是一个使用
    json
    序列化分数的示例(将分数存储在名称和分数之间的-a映射中):

    现在我们将创建一个函数,将分数写入给定的f