-1

The following code works, but when I open the CSV file it doesn't come up in alphabetical order or in any specific columns.

I would like name to come up in column 1 and the grade to appear in column 2 next to it. I had to put this in Tkinter and find it frustrating that I can't get it sorted. I am new to this and would be grateful for any advice.

from tkinter import * 
import csv

class App(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.output()
#output
    def output(self):
        Heading=StringVar()
        Heading.set("Please enter student name below")
        Label(text='Name:').pack(side=LEFT,padx=5,pady=5)
        self.n = Entry(root, width=10)
        self.n.pack(side=LEFT,padx=5,pady=5)
#Text label
        Label(text='Grade:').pack(side=LEFT,padx=5,pady=5)
        self.e = Entry(root, width=10)
        self.e.pack(side=LEFT,padx=6,pady=6)

        self.b = Button(root, text='Submit', command=self.writeToFile)
        self.b.pack(side=RIGHT,padx=5,pady=5)

        self.b = Button(root, text='Clear', command=self.writeToFile)
        self.b.pack(side=RIGHT,padx=5,pady=5)


#write to grade csv
    def writeToFile(self):
        with open('Grades.csv', 'a') as f:
            w=csv.writer(f, quoting=csv.QUOTE_ALL)
            w.writerow([self.n.get()])
            w.writerow([self.e.get()])


#I think it is here I need to add in some code to write the data to a certain row or column in my CSV file.

if __name__ == "__main__":
    root=Tk()
    root.title('grade')
    root.geometry('380x280')
    app=App(master=root)
    app.mainloop()
    root.mainloop()
CDspace
  • 2,639
  • 18
  • 30
  • 36
Niallm
  • 1
  • 1

1 Answers1

0

in order to write each name and grade in a separate column do this:

Switch

w.writerow([self.n.get()])
w.writerow([self.e.get()])

For

w.writerow([self.n.get(), self.e.get()])

There is already a question on how to sort a csv file alphabetically which has 3 answers which may help you:

How to sort data alphabetically in a csv file created in python?

Community
  • 1
  • 1
Tom Fuller
  • 5,291
  • 7
  • 33
  • 42