pythoncsvtkintercsvwriter

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


SO I've included some of my code having trouble capturing data from the entry fields in TKinter and having them overwrite a csv file. It will overwrite the csv file, but not add a new line at the end of the file like want.

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

Solution

  • w+ opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

    Therefore, use a instead , as opening a file with the a parameter allows you to append to the end of the file instead of simply overwriting the existing content.

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

    EDIT :

    csv.writer() function takes a csvfile as argument and you are passing lists:

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

    csv.writer(newline + main_lst)


    So, the correct way is using writerow() method:

    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)
    

    Also, for appending in the CSV file, it is suggested to use DictWriter() method. Refer here.