Issue with CSV reopening after appending data to it in Python

92 Views Asked by At

I have this working button and it does save, but my issue is I can start my tkinter program again from the same file. It works and if need more can share it, but the loop is where split from the csv for my columns in tkinter. Just can't get my python script to read it again once add data to it.

filePath = '..\glucose_values.csv'

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

  
#Store Button Function
    def store():
        with open('..\glucose_values.csv', "a", encoding='utf-8') as f:
            Writer= csv.writer(f)
            Writer.writerow(main_lst)
            messagebox.showinfo("Information","Saved succesfully")
           # df= pd.DataFrame(Data)
           # df.to_csv(f)
        return None
    
    
    
    def Add():
       #working
       lst=[timeEnter.get()]
       lst2=[dateEnter.get()]
       lst3=[bloodEnter.get()]
       main_lst.extend(lst+ lst2+lst3)
       print(lst)
       messagebox.showinfo("Information","The data has been added successfully")
       print(main_lst)
       return None
    
    def saveMe ():
        Add()
        global File
        #File =
        return None
    
    #GRab column informatin
    list_of_dates = []
    list_of_times =[]
    list_of_blood=[]
    #list_of_
    for x in list(range(0, len(Data))):
        list_of_dates.append(Data[x][0])
        list_of_times.append(Data[x][1])
        list_of_blood.append(Data[x][2])
1

There are 1 best solutions below

0
On

The for loop is more complex that you need, try something like:

>>> l = ['a', 'b', 'c']
>>> for i in range(len(l)):
...     print(l[i])
... 
a
b
c

no need for list(range(0, len(Data)))

also, do not use a global File.

Create a method to read the data, and another to save the data, and open your file as needed, like:

def read_data(filePath):
    with open(filePath) as myCsvFile:
        reader = csv.reader(myCsvFile)
        data = list(reader)

    return data 

using with you are sure that the resource (the file) is closed when you do not use it anymore

Finally, try to not use uppercase for instances of variables https://peps.python.org/pep-0008/#naming-conventions