在 Python 中使用 TKinter 将新行保存并添加到 csv 文件

Saving and adding a new line to a csv file with TKinter in Python

所以我已经包含了我的一些代码,这些代码无法从 TKinter 的输入字段中捕获数据并让它们覆盖 csv 文件。它会覆盖csv文件,但不会像想要的那样在文件末尾添加新行。

#Variables
File = open(filePath)
Reader = csv.reader(File)
newline='\n'
Data= list(Reader)
main_lst=[]

#Store Button Function
def store():
    with open('./glucose_values.csv', "w+", encoding='utf-8') as f:
        Writer=csv.writer(File)
        csv.writer(["Date","Time","Glucose"])
        csv.writer(newline + main_lst)
        messagebox.showinfo("Information","Saved succesfully")
                
    return None

def Add():
   lst=[timeEnter.get(),dateEnter.get(),bloodEnter.get()]
   main_lst.append(lst)
   messagebox.showinfo("Information","The data has been added successfully")
   return None

#Buttons 
storeButton = Button(root, text="Store", command=store)
storeButton.grid(row=5, column=3 )

addButton = Button(root, text="Add", command=Add)
addButton.grid(row=5, column=1 )

#Enter data area
dateEnter= Entry(root, width = 10).grid(row=13, column=2)
timeEnter= Entry(root,  width = 10).grid(row=14, column=2)
bloodEnter= Entry(root,  width = 10).grid(row=15, column=2)

w+ 打开文件进行读写。 如果文件存在,则覆盖现有文件。如果文件不存在,则创建一个新文件进行读写。

因此,请改用 a,因为使用 a 参数打开文件允许您追加到文件末尾 而不是简单地覆盖现有内容。

 with open('./glucose_values.csv', "a", encoding='utf-8') as f:
        Writer=csv.writer(File)

编辑:

csv.writer() 函数将 csv 文件作为参数并且您正在传递列表:

csv.writer(["Date","Time","Glucose"])

csv.writer(newline + main_lst)


所以,正确的方法是使用writerow()方法:

def store():
    with open('./glucose_values.csv', "a+", newline='', encoding='utf-8') as f:
        Writer=csv.writer(f)
        Writer.writerow(["Date","Time","Glucose"])
        Writer.writerow(main_lst)

另外,在CSV文件中追加,建议使用DictWriter()方法。 Refer here.