如何创建字典并将数据保存到文本文件? (测验游戏python)

时间:2016-01-22 22:22:39

标签: python list dictionary

这是python,我使用的是空闲版本3.4.2。 所以目前我的代码有效,但我想调整它以便能够: 保存名称的最新三个分数(因为它们重新运行代码并且分数保存在文本文件中)。然而,存在一个问题,无论输入什么“名称”,它都会用分数保存在自己的行上,而不是“附加”(我知道这是因为它不是以列表/字典的形式保存,而是如何我这样做了? - 或者我读到你可以“拆分”这条线?)

这是我的第一个问题,如果有人能提供帮助,我会非常感激,我是python的新手,所以这对我来说是一个挑战!任何意见或建议都非常欢迎!

import random #import module
print("What is your name?") #prints writing in brackets
name = input().title() #Capitalizes the first letter of the word inputted
print("What class are you in? (Enter 1, 2 or 3)") #asks the user to input a number

while True:
   try:
       class_number = int(input()) #asks for an integer input from user
   except ValueError: 
       print("Sorry, I didn't understand that, please try again") #print statement
       continue

   if class_number > 3: #if input is more than 3
       print("SORRY but that class isn't recognised, try again") #print statement
       continue
   else:
       print ("Hello,", name, "from class", class_number, "welcome to my quiz") #prints writing in brackets and anything saved in the variable "name" and "class_number"
       break #break out of loop

score = 0  #sets the variable "score" to zero
question = 0 # sets the variable "question" to zero

while question < 3:#If questions (intitally set to 0) is smaller than 10, carry out this function
   question +=1 # add one to the value of "question"
   maths = random.randint(1,3) #randomly generate a number from 1-3 and store as "maths"
   num1 = random.randint(1,10)#randomly generate an integer from 1-10 and store as "num1"
   num2 = random.randint(1,10)#randomly generate a second integer from 1-10 and store as "num2"
   if maths == 1: #if the number generated is 1 
       print(num1, "+", num2) #prints num1 + num2
       ans = num1 + num2 #sets "ans" to equal the value of num1 added to num2

   elif maths == 2: #if the number generated is 1
       print(num1, "*", num2) #print num1 multiplied by num2
       ans = num1 * num2 #sets "ans" to equal the value of num1 multiplied by num2

   else: #else run this part of code
       print(num1, "-", num2) #print num1 subtracted by num2
       ans = num1 - num2 #sets "ans" to equal the value of num1 subtracted by num2

   while True:
       try:
           user_ans = int(input()) #user inputs answer to question
       except ValueError: #runs when the user input is no an integer
           print ("SORRY but that answer isn't recognised, try again")
       else:
           break

   if user_ans == ans:
       score+=1
       print("Well done, you are CORRECT")

   else:
       print("SORRY, you are INCORRECT") #print writing in brackets
       print("The correct answer was", ans)

if score == 10: #run this part of code if "score" equals 10
       print("fantastic", name, "you got full marks!") #print statement and name 
elif score >= 6: #run this part of code if "score" is larger than or equal to 6
       print("well done, there's some improvement to be done here though", name, "you got", score, "/10")# then print statement and score
elif score <=5: #run this part of code if "score" is smaller than or equal to 5
       print("hmm, maybe some more practise would be beneficial", name, "you got", score, "/10") #then print statement and score

class_number = str(class_number) + ".txt" #this adds '.txt' to the end of the file (therefore creating a text file) so it can be used to create a file under the name of the class
file = open(class_number, 'a') #opens the file in 'append' mode so you don't delete all the information
file.write(str(name + " : ")) #writes the name and ":" to file
file.write(str(score)) #writes the score to file
file.write('\n')#writes the score to the file
file.close()#safely closes the file to save the information

view = int(input("would you like to view the scores? If yes, press 1 or not press 2"))
if view == 1:
   exit
elif view == 2:
   exit #to be completed

5 个答案:

答案 0 :(得分:1)

如果您想将用户的分数保存到列表中......

my_list = []
my_list.append(score)

您可能希望在游戏开始前阅读文件。然后,您需要使用文本文件中的分数填充列表。

with open(class_number) as scorefile:
    for line in scorefile:
        my_list.append(line)

最后,当游戏结束时,您想要将用户的分数添加到文件中。在这种情况下,我会保持简单,并且不包括该人的姓名,但您仍然可以将该行添加到列表中。

f = open(class_number 'w')
f.write("\n" + score)
f.close()

然后,如果他们查看分数,只需打印my_list的值,用新行分隔列表中的每个元素。

答案 1 :(得分:1)

如果你想让它保持人类可读性,请将它写在json文件中:

import json

your_dictonary = {"my_key":"one_value"}

str_to_save = json.dumps(your_dictonary)
# Then write it to a file as you did before

加载几乎一样容易:

json.loads(file_content) # after you read the file as usual

答案 2 :(得分:0)

使用pickle模块存储您的数据。将您的user => score关系组织到字典中,然后调用pickle.dump(filename, theDict)将其保存到文件中。

当您需要它时,请致电theDict = pickle.load(filename),它将从pickle文件加载数据。这种方法比你必须设计自己的解析算法要好。

答案 3 :(得分:0)

如果您可以更改文件的外观,请尝试saving the file as json

在代码的顶部,加载文件中的分数:

import json
with open('{}.txt'.format(class_number)) as f:
    scores = json.load(f)

然后,您可以修改字典中的分数并写回文件:

scores[name] = score
with open('{}.txt'.format(class_number)) as f:
    json.dump(scores, f)

此代码不会存储超过最新分数的内容,但您可以探索为每个名称保存多个分数的选项。我建议看看defaultdict

答案 4 :(得分:0)

有些答案建议将分数存储为JSON(好主意)或腌制它们(糟糕的主意!it's dangerous)。这个答案假定您要保留平面文件,最早的格式。

您正在以附加模式打开文件,因此您将无法更改任何内容。要进行更改,您首先需要阅读文件:

try:
    fileh = open(class_number, 'r')
    oldlines = fileh.readlines()
    fileh.close()
except IOError: # If we didn't find the file, there were no old scores
    oldlines = []

请注意,这会读取所有行;如果你的文件变得非常大,它将不会全部适合内存,你应该逐行阅读并随时写。

对于每一行:

  • 如果这是另一个人的分数,你没有理由触及它,只需逐字写回。
  • 如果是这个人的分数,请保留它,如果它是最近的两个之一。

如果我们从最近的一行开始,跟踪最近的分数会稍微容易一些,所以让我们这样做:

updatedlines = []
recentscores = 0
for line in oldlines[::-1]: # go backwards, most recent line first
    (lname, lscore) = line.split(" : ") # read the name and the score from the line; this will break if the name contains " : "
    if lname == name:
        recentscores += 1 # keep track of how many scores we have for this person
        if recentscores <3:
            updatedlines.append(line)
    else:
            updatedlines.append(line)

updatedlines = updatedlines[::-1] # put the lines back in the right order

最后,添加新分数。

updatedlines.append("%s : %d\n" % (name, score))

现在我们可以将这些行写回文件:

fileh = open(class_number, 'w')
fileh.writelines(updatedlines)
fileh.close()