所以我有一个学校作业来创建一个GUI,允许我将学生添加到我所创建的数据库中。我想出了如何搜索学生,但我正在努力增加学生。我需要将此数据导出为CSV文件。我设法导出它,但它带有逗号,语音标记和括号,我不想要。到目前为止,这是我的代码,对于不起作用的部分:
def reveal(self):
firstname = ("Forename: ", self.forename_entry.get())
lastname = ("Surname: ", self.surname_entry.get())
gender_ = ("Gender: ", self.gender_entry.get())
birthdate = ("DOB: ", self.DOB_entry.get())
Student_ID = ("Student ID Number: ", self.studentID_entry.get())
home = ("Address: ", self.address_entry.get())
phone = ("Home phone number: ", self.homephone_entry.get())
group = ("Tutor Group: ", self.tutorgroup_entry.get())
school_email = ("School Email", self.sch_email_entry.get())
with open("StudentIDs.csv", "a") as f:
w = csv.writer(f, quoting = csv.QUOTE_ALL)
writeit = (['\n', firstname, '\n', lastname, '\n', gender_, '\n', birthdate, '\n', Student_ID, '\n', home, '\n', phone, '\n', group, '\n', school_email])
w.writerow(writeit)
self.invalidtext.configure(text = "Student added")
答案 0 :(得分:0)
从tuple
更改为dict
:
class csv.DictWriter(f, fieldnames, restval=”, extrasaction=’raise’, dialect=’excel’, *args, **kwds)
创建一个像常规编写器一样操作的对象,但将字典映射到输出行 fieldnames参数是一系列键,用于标识传递给writerow()方法的字典中的值被写入文件f的顺序。
record ={}
record["Forename"] = self.forename_entry.get()
record["Surname"] = self.surname_entry.get()
... an so on
with open("StudentIDs.csv", "a") as f:
w = csv.DictWriter(f, fieldnames=list(record.keys()))
if firstRow:
w.writeheader()
w.writerow(record)