Incrementing Counter for button clicks

I want the value of a and b to be incremented every time I click the respective button and save that value in a txt file. Can you help me with the error as I’m not able to save the file neither increment it

if st.button('Login'):
        if (title in (245642504 , 243480100 , 278313783 , 151065371 , 251879409 , 230970866 , 287758725 , 231166811 , 237868680 , 282432370)):
            #a=0
            data = pd.read_csv("version1.csv",sep=";")  
            df1 =  data['UserId']==title
            df2 =data[df1]
            if  df2.empty:
                
                st.write('No User Found')
            else:
                st.write(data[df1]) 
                #st.image(data[df1['3'][2], use_column_width=None)
            
            data2 = pd.read_csv("PopularItems.csv")  
            df3 =  data2['UserID']==title
            df4 =data2[df3]
            st.markdown("<h1 style='text-align: left; color: blue;'>userID</h1>", unsafe_allow_html=True)
            if df3.empty:
                st.markdown("<h1 style='text-align: left; color: blue;'>empty</h1>", unsafe_allow_html=True)
                st.write('No User Found')
            else:
                st.write(data2[df3]) 
                #st.image(data[df1['3'][2], use_column_width=None)
            if st.button ('Buy'):
                
                a= 1
                st.markdown("<h1 style='text-align: left; color: blue;'>userID</h1>", unsafe_allow_html=True)
                with open('svd.txt', 'w') as f:
                    
                    f.write('%d' % a)   
                    f.close()

Hi @Bishop_Sankhe, welcome to the Streamlit community!

This took a little more thinking than I expected! But you should be able to do this using the following:

import streamlit as st


with open("file.txt", "r") as f:
    a = f.readline()  # starts as a string
    a = 0 if a == "" else int(a)  # check if its an empty string, otherwise should be able to cast using int()

if st.button("Click me"):
    a += 1  
    with open("file.txt", "w") as f:
        f.truncate()
        f.write(f"{a}")

a