Jagraj Singh
Jagraj Singh

Reputation: 19

Write list to CSV file in Python

I have created a quiz for students to take part to test their arithmetic skills. I wish to write the list of students and their scores to a csv file. I am struggling to write to file and although I have managed to, the excel file contains no data. It says "Score for [] : []". Very sorry for the inefficient code, but any help will do on how to solve this.

I created 2 empty lists and a variable.

Student = []
Score = []
QuizTaken = 0

This defines when to append the scores to the list.

def QuizTaken(): #the amount of quizzes taken by student

    while QuizTaken <= 3:

        userName, ClassName = Introduction() #used to input name and class using raw_input
        score = Quiz()

        Student.append(userName) #student's inputted name is appended to list
        Score.append(score) #student's final score is appended to list

QuizTaken()

This code writes the list to file in the form of a string, however I think my problem lies here somewhere, however I can't locate it.

def WriteToFile():

   userName, ClassName = Introduction()
   score = Quiz()

   print ""

   if ClassName == "10x1":
       print "Creating a text file for your teacher..."
       fileWrite = open("10x1 Class Score.csv", "a+") 
       fileWrite.write("Score for ")
       fileWrite.write(str(Student))
       fileWrite.write(" : ")
       fileWrite.write(str(Score))
       fileWrite.write("\n")
       fileWrite.close()

The code should write the names and scores appended into the empty list into a csv file, with the data available for me to view, but it shouldn't be overwritten.

Upvotes: 1

Views: 218

Answers (1)

lgd
lgd

Reputation: 1462

There are a few problems with your code: you have QuizTaken as both function and variable name. You also don't increment your counter (QuizTaken) in the body of your loop. You can use pandas (http://pandas.pydata.org/) to store your data in dataframe and then use pandas.DataFrame.to_csv() to write it to a file.

Upvotes: 1

Related Questions