首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何创建字典并将数据保存到文本文件?(竞猜游戏python)

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

Stack Overflow用户
提问于 2016-01-23 06:22:39
回答 5查看 378关注 0票数 0

这是python,我使用的是idle版本3.4.2。因此,目前我的代码可以工作,但我想对其进行调整,以便能够:将最近的三个分数保存为名称(因为它们会重新运行代码,并且分数将保存在文本文件中)。然而,有一个问题是,无论输入什么"name“,它都会将分数重新保存在自己的行中,而不是”追加“(我知道这是因为它不是以列表/字典的形式保存的,但我该如何做呢?--或者我读到你可以”拆分“该行?)

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

代码语言:javascript
复制
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
EN

回答 5

Stack Overflow用户

发布于 2016-01-23 06:46:02

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

代码语言:javascript
复制
my_list = []
my_list.append(score)

你可能也想在游戏开始前读入文件。然后,您需要用文本文件中的分数填充列表。

代码语言:javascript
复制
with open(class_number) as scorefile:
    for line in scorefile:
        my_list.append(line)

最后,当游戏结束时,您需要将用户的分数添加到文件中。在本例中,我将保持简单,不包括示例中的人名,但您仍然可以将该行添加到列表中。

代码语言:javascript
复制
f = open(class_number 'w')
f.write("\n" + score)
f.close()

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

票数 1
EN

Stack Overflow用户

发布于 2016-01-23 06:46:59

如果您想让它保持人类可读,请将其写在一个json文件中:

代码语言:javascript
复制
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

加载几乎同样简单:

代码语言:javascript
复制
json.loads(file_content) # after you read the file as usual
票数 1
EN

Stack Overflow用户

发布于 2016-01-23 06:45:25

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34956917

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档