【问题标题】:Storing data from a python program onto an excel/notepad document将 python 程序中的数据存储到 excel/记事本文档中
【发布时间】:2015-01-07 12:33:53
【问题描述】:

我制作了一个 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()

【问题讨论】:

标签: python database storage export-to-excel


【解决方案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

【讨论】:

    【解决方案2】:

    记事本:

    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 安装 xlsxwriter

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-01
      • 1970-01-01
      • 2013-04-28
      • 1970-01-01
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多