如何仅保存最新的输入 - Python

时间:2015-04-30 09:35:27

标签: python

如何实施一个只能保存学生最新3分的简单代码?如果稍后重复测试,则应更换旧分数。

谢谢。

这是向用户询问问题并将结果保存在txt中的代码。文件。

import random
import math
import operator as op

correct_answers = 0

def test():
    num1 = random.randint(1, 10)
    num2 = random.randint(1, 10)

ops = {
    '+': op.add,
    '-': op.sub,
    '*': op.mul,
}

keys = list(ops.keys()) 
rand_key = random.choice(keys)  
operation = ops[rand_key]  

correct_result = operation(num1, num2)

print ("What is {} {} {}?".format(num1, rand_key, num2))
user_answer= int(input("Your answer: "))

if user_answer != correct_result:
    print ("Incorrect. The right answer is {}".format(correct_result))
    return False
else:
    print("Correct!")
    return True

username = input("What is your name? ")
print("Hi {}! Welcome to the Arithmetic quiz...".format(username))
class_name = input("Are you in class 1, 2 or 3? ")
correct_answers = 0
num_questions = 10

for i in range(num_questions):
    if test():
        correct_answers +=1


print("{}: You got {}/{} questions correct.".format(
    username, 
    correct_answers, 
    num_questions,

))

class_name = class_name + ".txt"    #creates a txt file called the class    that the user entered earlier on in the quiz.

file = open(class_name , 'a')   #These few lines open and then write the    username and the marks of the student into the txt file.
name = (username)
file.write(str(username + " : " ))  
file.write(str(correct_answers))
file.write('\n')    #This puts each different entry on a different line.
file.close()    #This closes the file once the infrmation has been written.

1 个答案:

答案 0 :(得分:1)

更好的解决方案是以不同的格式存储数据,使一切变得简单。例如,如果您使用shelve数据库将每个用户名映射到deque个答案,那么整个事情就是这么简单:

with shelve.open(class_name) as db:
    answers = db.get(username, collections.deque(maxlen=3))
    answers.append(correct_answers)
    db[username] = answers

但是如果你不能改变数据格式,并且你只需要在人类可读的文本文件的末尾附加新行,那么只想知道是否已有3个答案是通读文件中的每一行都可以看到已有多少行。例如:

past_answers = []
with open(class_name) as f:
    for i, line in enumerate(f):
        # rsplit(…,1) instead of split so users who call
        # themselves 'I Rock : 99999' can't cheat the system
        name, answers = line.rsplit(' : ', 1)
        if name == username:
            past_answers.append(i)

如果有3个过去的答案,你必须重写文件,跳过#i行。这是非常有趣的部分;文本文件不是随机访问可编辑的,因此您可以做的最好是将其全部读入内存并将其写回,或将其全部复制到临时文件并将其移动到原始文件上。像这样:

excess_answers = set(past_answers[:-2])
if excess_answers:
    with open(class_name) as fin, tempfile.NamedTemporaryFile() as fout:
        for i, line in enumerate(fin):
            if i not in excess_answers:
                fout.write(line)
        os.replace(fout.name, fin)

该部分未经测试。它需要Python 3.3+;如果您有早期版本,并且在Mac或Linux上,则可以使用os.rename而不是replace,但如果您使用的是Windows ...那么您需要做一些研究,因为它很丑陋且没有乐趣

现在,您最终可以添加新答案,就像您已经在做的那样。