简体   繁体   中英

How would I save the data to a .csv file

I have made a program based on a maths quiz and have saved the data of the files to a .txt file. If I wanted to save the files in a .csv file would i just chnage .txt to .csv? Here is my code :

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.

This is my code would I need to change the bottom of the code to save the files in a .csv file. I tried doing a different method, but never got anywhere .

I suggest using the csv module. I've adapted your code to use it (there are a lot of ways you could make your life easier with your code, but let's focus on one issue at a time):

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")

Gentle into to the csv module

Because we're using the with keyword , there is no need to call file.close()

For a more advanced way of doing this, you could use pandas to_csv

Looks like your Class1 is simply a list. Then you can say file.write(",".join(Class1)) . But a more robust method is to use the csv module - https://docs.python.org/2/library/csv.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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