将python程序中的数据存储到excel / notepad文档中

时间:2015-01-07 12:33:54

标签: python database storage export-to-excel

我制作了一个python程序,询问10个随机数学问题,然后在下面粘贴我的程序时显示得分。我想编辑/改进我的程序,以便它可以存储每个人和每个班级的分数,它应该存储在excel或记事本文档中。请帮我编辑程序,并告诉我哪种功能最适合存储这类数据。请解释一下,尽可能简单,因为我是python的初学者所以我不知道很多函数或程序。

import random
def questions():
    name=input("What is your name: ")
    print("Hello there",name,"! Please answer 10 random maths questions for this test!")

    choice = random.choice("+-x")
    finish = False
    questionnumber = 0
    correctquestions = 0

    while finish == False:
        choice = random.choice("+-x")
        if questionnumber < 10 | questionnumber >= 0:
            number1 = random.randrange(1,10)
            number2 = random.randrange(1,10)
            print((number1),(choice),(number2))
            answer=int(input("What is the answer?"))
            questionnumber = questionnumber + 1

            if choice==("+"):
                realanswer = number1+number2
                if answer==realanswer:
                    print("That's the correct answer")
                    correctquestions = correctquestions + 1
                else:
                    print("Wrong answer, the answer was",realanswer,"!")

            if choice==("x"):
                realanswer = number1*number2
                if answer==realanswer:
                    print("That's the correct answer")
                    correctquestions = correctquestions + 1
                else:
                    print("Wrong answer, the answer was",realanswer,"!")

            elif choice==("-"):
                realanswer = number1-number2

                if answer==realanswer:
                    print("That's the correct answer")
                    correctquestions = correctquestions + 1
                else:
                    print("Wrong answer, the answer was",realanswer,"!")
        else:
            finish = True
    else:
            print("Good job",name,"! You have finished the quiz")
            print("You scored " + str(correctquestions) + "/10 questions.")

questions()

2 个答案:

答案 0 :(得分:1)

写入excel文件的最简单方法是:

score="20"
f = open('example.csv','w')
f.write(score)
f.close()

您还可以使用xlwt库来创建可以填充信息的新工作簿对象。

score=20
name="Mark"

import xlwt
book = xlwt.Workbook(encoding="utf-8")
sheet1 = book.add_sheet("Sheet 1") 
sheet2 = book.add_sheet("Sheet 2") 
sheet1.write(0, 0, str(score))             #write score to cell(0,0) in Sheet 1
sheet1.write(0, 1, name)                   #write name to cell(0,0) in Sheet 1
book.save('book3.xls')                     #the workbook will be saved as "book3.xls" in your working directory

要重写到同一工作簿,您可以使用:

score2=40
name2="Peter"

from xlrd import *
w = copy(open_workbook('book3.xls'))
w.get_sheet(0).write(1,0,str(score2))        #write score to cell(1,0) in Sheet 1
w.get_sheet(0).write(1,1,name2)              #write name to cell(1,1) in Sheet 1
w.save('book3.xls')

生成的excel文件如下所示:

#20 Mark
#40 Peter

答案 1 :(得分:0)

对于记事本:

scores = {"name_1" : 10, "name_2" : 20, "name_3" : 30}      # your score data
my_file = open('scores.txt', 'w')                           # create the file
for name in scores:                                         # the loop
    my_file.write(name + ": " + str(scores[name]) + "\n")   # write score line by line
my_file.close()                                             # close the file

对于Excel,请使用xlsxwriter

import xlsxwriter
workbook = xlsxwriter.Workbook('scores.xlsx')          # create the workbook
worksheet = workbook.add_worksheet()                   # add a sheet
scores = {"name_1" : 10, "name_2" : 20, "name_3" : 30} # your score data
i = 0                                                  # line index
for name in scores:                                    # the loop
    worksheet.write(i, 0, name)                        # write name at line i and column 0
    worksheet.write(i, 1, scores[name])                # write score at line i and column 1
    i += 1                                             # increment the line index
workbook.close()                                       # close the workbook

使用pip安装xlsxwriter:

  

pip install xlsxwriter