尝试将整数输入到文件中并将其作为一个整数检索。Python 3x

尝试将整数输入到文件中并将其作为一个整数检索。Python 3x,python,python-3.x,testing,Python,Python 3.x,Testing,所以我一直在尝试学习Python,我有一个小应用程序来进行英语测试。但是我想把‘score’放到一个文件中,但不是作为字符串,而是作为一个整数。然后我也想把它作为一个整体拿出来 同时,如果“名称”是新的,我有时会创建文件,因此我想检查文件是否为空,如果为空,则在其中添加一个0。有什么建议吗 当然,如果你有任何其他批评,我很乐意听到:) 最简单的方法可能是将其作为字符串写入,然后将其作为字符串读回: file = open(filename, 'w') file.write(str(score))

所以我一直在尝试学习Python,我有一个小应用程序来进行英语测试。但是我想把‘score’放到一个文件中,但不是作为字符串,而是作为一个整数。然后我也想把它作为一个整体拿出来

同时,如果“名称”是新的,我有时会创建文件,因此我想检查文件是否为空,如果为空,则在其中添加一个0。有什么建议吗

当然,如果你有任何其他批评,我很乐意听到:)


最简单的方法可能是将其作为字符串写入,然后将其作为字符串读回:

file = open(filename, 'w')
file.write(str(score))
后来:

score = int(file.read())
file = open(filename)
score = pickle.load(file)
然而,如果你想用二进制写它(比如说把分数弄糊涂一点),有很多选择。虽然可以肯定地说,使用标准整数编码编写它,但如果我想序列化数据,我通常只使用pickle模块:

import pickle

file = open(filename, "w")
pickle.dump(score, file)
file.close()
后来:

score = int(file.read())
file = open(filename)
score = pickle.load(file)
我喜欢这种方法,因为它适用于序列化任何类型的数据,而不仅仅是整数。如果这是你真正想要的,请看这篇文章,了解一些关于用完全二进制编写或阅读的线索:


最后,因为您要求提供其他反馈:如果我正在实施此操作,并且我不希望有一个庞大的数据集,我只会将所有分数存储在一个字典中,然后根据需要将该字典pickle并解pickle到一个文件中。

如果您想要持久化数据,使用dict和pickle将是一个很好的方法,您可以使用单个文件并使用名称来查找用户,就像您自己的方法一样,尽管如果两个用户的名称相同,您会遇到问题,因此您可能需要考虑如何让每个用户选择uniqe标识符:

questions = ["1. You won't find Jerry at home right now. He ______________ (study) in the library.",
             "2. Samantha ______________   (do) her homework at the moment.",
             "3. We______________  (play) Monopoly a lot.",
             "4. Ouch! I ______________ (cut, just) my finger!",
             "5. Sam (arrive) ______________in San Diego a week ago."]
keys = ["is studying",
        "is doing",
        "play",
        "have just cut",
        "arrived"]

import pickle


def ask(scores):
    print("Type in the verb given in brackets in the correct form.\n")
    # this loop asks questions and determines whether the answer is right
    # if new user default score to 0
    score = scores.get(name, 0)

    # zip the questions and answer together
    for q, a in zip(questions, keys):
        print("Your current score is: %d" % score)
        answer = input(q)
        if answer == a:
            print("You are right! You get one point")
            score += 1
        else:
            print("Wrong! You lose one point!")
            # don't want minus scores.
            if score > 0:
                score -= 1
    # update or create user name/score pairing and dump to file
    scores[name] = score
    with open("score.pkl", "wb") as f:
        pickle.dump(scores, f)


# creates a file with the person's name
print("Hello. This is an English test.")
name = input("What is your name?")


try:
   # first run file won't exist 
    with open("score.pkl", "rb") as f:
        scores = pickle.load(f)
except IOError as e:
    print(e)
    scores = {}

ask(scores)

不能将其作为整数放入文件中。只需读取并在读取后将其转换为int。使用
pickle.dump
pickle.load
,使用dict将带有分数列表的名称存储为值,这将使文件只能包含字符串变得更容易。如果要使用
.write()
方法,需要给它一个字符串。但是,你可以使用。请检查你的代码,该代码只会对我尖叫
SyntaxError
。在程序中写入分数不会让它们保留到下次使用程序tho,对吗?当我想检查我的学生的表现时,我需要分数。谢谢你在这方面做了这么多的工作!我现在要去试着理解每一部分的作用:D这里有很多新的东西:这一行是怎么回事:分数[名字]=分数,因为分数随着每个答案的增加或减少,所以这不应该是相反的吗?新的分数更新到了名字旁边的字典里?加上为什么它是一个方括号而不是一个卷曲的?这是一本字典,我们正在搜索“名称”对吗?@OmenofCode,因为我们是通过键访问字典的,如果用户不存在,分数默认为0,
score=scores.get(name,0)
如果它存在分数,我们添加/更新新分数,然后
scores[name]=在我们将dict转储到磁盘之前,将分数
更改为新分数