【问题标题】:Trying to get my data to write to specific columns and to sorted in alphabetical order试图让我的数据写入特定列并按字母顺序排序
【发布时间】:2016-09-30 13:54:14
【问题描述】:

以下代码有效,但当我打开 CSV 文件时,它不 按字母顺序或任何特定列出现。

我希望 name 出现在 第 1 列grade 显示在其旁边的第 2 列中。我不得不把这个放进去 Tkinter 并发现我无法对其进行排序感到沮丧。 我是新手,如果有任何建议,我将不胜感激。

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

【问题讨论】:

    标签: sorting csv tkinter


    【解决方案1】:

    为了将每个姓名和等级写在单独的列中,请执行以下操作:

    切换

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

    对于

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

    已经有一个关于如何按字母顺序对 csv 文件进行排序的问题,其中有 3 个答案可能对您有所帮助:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-16
      • 2015-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多