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

2024-04-26 20:48:00 发布

您现在位置:Python中文网/ 问答频道 /正文

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

同时,我有时会创建文件,如果'名称'是新的,所以我想检查文件是否是空的,如果是,把一个0在那里。有什么建议吗?你知道吗

当然,如果你还有其他批评的话,我很乐意听到:)

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"]

print("Hello. This is an English test.")
name = input("What is your name?")

#creates a file with the person's name
file = open("%sScore.txt" % name, "w+")

#reads that person's score
score = file.read()

#if there is nothing in the file it puts in 0
if (len(score) == 0):
file.write(bytes('0'), "UTF-8")

print("Type in the verb given in brackets in the correct form.\n")

#this loop asks questions and determines whether the answer is right
for i in range (0, 4):
print("Your current score is: %d" % score)
answer = input("%s" % questions[i])
if(answer == "keys[i]"):
    print("You are right! You get one point")
    score = score + 1
else :
    print("Wrong! You lose one point!")
    score = score - 1

#end of the test and writing the score to the file
print("Congratulations! You finished the test. Your score is %d" % score)
file.write(bytes("%d" % score, "UTF-8"))

file.close()

Tags: 文件theanswernameintestrightyou
2条回答

如果要持久化数据,使用dict和pickling将是一种很好的方法,您可以使用单个文件并使用名称来查找用户,就像您自己的方法一样,但如果两个用户的名称相同,则会出现问题,因此您可能需要考虑如何让每个用户选择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)

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

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

稍后:

score = int(file.read())

但是,如果你想用二进制写的话(比如说把分数弄模糊一点),有很多选择。虽然可以肯定地说,使用标准整数编码编写它,但如果我想序列化数据,我通常只使用pickle模块:

import pickle

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

稍后:

file = open(filename)
score = pickle.load(file)

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

Reading a binary file with python

最后,因为您要求其他反馈:如果我正在实现这个,并且我不希望有一个庞大的数据集,我只会将所有的分数存储在一个字典中,然后根据需要将该字典pickle和unpickle到一个文件中。你知道吗

相关问题 更多 >