繁体   English   中英

我如何将数据保存到 .csv 文件

[英]How would I save the data to a .csv file

我根据数学测验制作了一个程序,并将文件数据保存到 .txt 文件中。 如果我想将文件保存在 .csv 文件中,我是否只需将 .txt 更改为 .csv? 这是我的代码:

import time
import math 
import random#I am using this to allow me to randomly pick the symbol operation and to randomly generate numbers
print("Title:Arithmetic Quiz")#Tells the user what the program is.
print("*************************************************************")#This is a line to make the presentation clearer to the user.
#The code below shows the user an introduction of what the program is about.
print("This program will ask you to complete the arithmetic quiz.")
print("The program has 10 questions. You will recieve feedback after.")
print("____________________________________________________________")
#The line above prints a line across the page.
while True:#This creates an infinity loop
    UserName = input("What is your name?:")#Ask the user for there name.
    if not UserName.isalpha():#This is used to check if the user name is anything else apart from alphabetical letters.
        print("Error!Please enter your name using letters. ") #warning if wrong if wrong input given
        continue#Continues with the code when correct input given.
    else:#It breaks out of the while loop and proceeds with the quiz
        break
ClassSelection= input("Please enter what Class you are in?:1, 2 or 3")
ClassChosen=0
while ClassChosen==0:
    if ClassSelection=="1":
        ClassChosen=1
    elif ClassSelection=="2":
        ClassChosen=1
    elif ClassSelection=="3":
        ClassChosen=1
    else:
        print("You must write 1, 2, or 3.")
        ClassSelection=input("Enter the class you are in")


print(UserName," welcome to the Arithmetic Quiz.")#Welcomes the user to the quiz.
print("____________________________________________")
print("The quiz will begin in 3 seconds")
time.sleep(2)
for i in range(0,3):# range between 
    print (3 - i)#counts down by one
    time.sleep(1)#Delays for 1 second
print("Begin!")
print("*****************************************")
RecentStudent= [0,0,0]#This is a list with dummy values. The use of this is to save the last three score of the user.
def MathsQuiz():#I have used a function to make my code more efficient.
    score=0#No questions have been answered correctly yet so score is set to zero 
    for questionNum in range(10):#I have used this to allow me to set my Parameters.
        Num1= random.randint (1, 10)#Generates a random number between 1 and 10 for Num1.
        Num2= random.randint (1, 10)#Generates a random number between 1 and 10 for Num2
        Symbol = ["+","-","*"]#These are my operators used for the arithmetic of Num1 and Num2.
        Operation = random.choice(Symbol)#This will randomly choose a operating symbol for a question
        RealAnswer= int(eval(str(Num1)+Operation+str(Num2)))#This is used to work out the answer for the question.The evaluate is used to interpret the code as a str and calculate an answer.
#It will store the value of the Answer and call it when it is needed.
        print("Please give an answer for:", Num1, Operation, Num2)#This is what makes the question and outputs it to the user by using the random functions.        
        UserAnswer = int(input("Enter your answer here:"))#This asks the user to enter their anser to the question.
        if UserAnswer == RealAnswer:#This checks if the answer from the user is the same as the real answer.
            score = score + 1#If the user gets the question right 1 should be added to the score.
            print("You are correct! :D")#The program will congratulate the user.
            print("_______________________________________________")
        else:#If the users answer is not the same as the real answer then it will print a wrong message.
            print("You are incorrect! :( ")#This tells the user that they got the question incorrect and tells the user the real answer.
            print("The answer was", RealAnswer)
            print("________________________________________________")#This will be used to split the quiz.
    print()#This is used to format the quiz.
    print("__________________________________________________")
    print("Thank you for completing the quiz!")
    print("Your Score is loading")
    import time
    time.sleep(2)
    print(UserName,"In this test you achieved",score,"/10")#This tells the user the score they achieved in the maths test.
    print()#This is used to format the code
    del RecentStudent[0]
    RecentStudent.append(score)
    print("Your three most recent scores are:",RecentStudent)
    print("********************************************************")
def Resit1():#This function is used to easily call place of the program such as in this case when resitting.
    Resit1=input("Do you want to resit the test? Yes or No?:")#Asks the user if they would like to resit

    #The variable will let user input whether they want to do the quiz again.
    if Resit1== "Yes" or Resit1=="yes":# Checks the input of the user to the resit question
        MathsQuiz()#This is used to call the quiz which will restart the quiz and allow them to retake the quiz.
    #It tells the user that they are finished 


def Resit2():#This function is used to easily call place of the program such as in this case when resitting.
    Resit2=input("Do you want to resit the test? Yes or No?:")#Asks the user if they would like to resit

    #The variable will let user input whether they want to do the quiz again.
    if Resit2== "Yes" or Resit2=="yes":# Checks the input of the user to the resit question
        MathsQuiz()#This is used to call the quiz which will restart the quiz and allow them to retake the quiz.
        print("Quiz Finished")#It tells the user that they are finished 

MathsQuiz()#This will call the first function that has been set in the program.
Resit1()#This will call the Resit1 function when it is needed by the program.
Resit2()#This will call the Resit2 function when it is needed by the program.

if ClassSelection=="1":#used to identify whether the ClassSelection is equal to 1.
    Class1 = []#class1 list is created and is empty.
    Class1.append("Student: ")#This text is added as the first item of the list.
    #The text helps with presentation and makes the data more clear.
    Class1.append(UserName)#The name variable is appended as the second item.
    Class1.append("Latest 3 Scores: ")#This text is added so user knows the next item is score.
    Class1.append(RecentStudent)#The score variable is appended as the last item.


    file = open("Class1Scores.txt", 'a')#File opened called classAScores.
    #It is a text file because I added ".txt"
    #I used the mode 'a' because this allows me to append things to the file.
    file.write(str(Class1))#Allows me to write the classA list onto the file.
    #Because the mode is append, it enables me to append a whole list to the file.
    #the str() makes sure the list is interpreted as code as code can be appended.
    #The list in its raw form will not append to the file.
    file.write("\n")#Ensures the next pupils data is recorded on the row below.
    file.close()#Closes the file so everything is saved.

elif ClassSelection=="2":#used to identify whether the ClassSelection is equal to 1.
    Class2=[]#classA list is created and is empty.
    Class2.append("Student: ")#This text is added as the first item of the list.
    #The text helps with presentation and makes the data more clear.
    Class2.append(UserName)#The name variable is appended as the second item.
    Class2.append("Latest 3 Scores: ")#This text is added so user knows the next item is score.
    Class2.append(RecentStudent)#The score variable is appended as the last item.


    file = open("Class2Scores.txt", 'a')#File opened called classAScores.
    #It is a text file because I added ".txt"
    #I used the mode 'a' because this allows me to append things to the file.
    file.write(str(Class2))#Allows me to write the classA list onto the file.
    #Because the mode is append, it enables me to append a whole list to the file.
    #the str() makes sure the list is interpreted as code as code can be appended.
    #The list in its raw form will not append to the file.
    file.write("\n")#Ensures the next pupils data is recorded on the row below.
    file.close()#Closes the file so everything is saved.if ClassSelection=="1":#used to identify whether the ClassSelection is equal to 1.


elif ClassSelection==3:
    Class3 = []#classA list is created and is empty.
    Class3.append("Student: ")#This text is added as the first item of the list.
    #The text helps with presentation and makes the data more clear.
    Class3.append(UserName)#The name variable is appended as the second item.
    Class3.append("Latest 3 Scores: ")#This text is added so user knows the next item is score.
    Class3.append(RecentStudent)#The score variable is appended as the last item.


    file = open("Class3Scores.txt", 'a')#File opened called class3Scores.
    #It is a text file because I added ".txt"
    #I used the mode 'a' because this allows me to append things to the file.
    file.write(str(Class3))#Allows me to write the class3 list onto the file.
    #Because the mode is append, it enables me to append a whole list to the file.
    #the str() makes sure the list is interpreted as code as code can be appended.
    #The list in its raw form will not append to the file.
    file.write("\n")#Ensures the next pupils data is recorded on the row below.
    file.close()#Closes the file so everything is saved.

这是我的代码,我需要更改代码的底部以将文件保存在 .csv 文件中。 我尝试了一种不同的方法,但从未得到任何地方。

我建议使用csv模块。 我已经修改了您的代码以使用它(有很多方法可以让您的代码更轻松,但让我们一次只关注一个问题):

import csv

if ClassSelection=="1":#used to identify whether the ClassSelection is equal to 1.
    Class1 = []#class1 list is created and is empty.
    Class1.append("Student: ")#This text is added as the first item of the list.
    #The text helps with presentation and makes the data more clear.
    Class1.append(UserName)#The name variable is appended as the second item.
    Class1.append("Latest 3 Scores: ")#This text is added so user knows the next item is score.
    Class1.append(RecentStudent)#The score variable is appended as the last item.

    with open('Class1Scores.csv', 'wb') as file:
        writer = csv.writer(file)
        writer.writerow(str(Class1))
        writer.writerow("\n")

温柔进入csv模块

因为我们使用with关键字,所以不需要调用file.close()

要获得更高级的方法,您可以使用pandas to_csv

看起来您的 Class1 只是一个列表。 然后你可以说file.write(",".join(Class1)) 但更强大的方法是使用csv模块 - https://docs.python.org/2/library/csv.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM