Saving and reusing CSV data with st.data_editor

I am trying to create an editable dataframe by loading data from a csv file into a dataframe, and then passing it to the data_editor, which would return df_edited.

What I would like to have as a result, is this df_edited to be saved again and reused in the data_editor. Basically, for every change to be saved in the csv and reflected back in the data_editor.

df = pd.read_csv('test.csv')

df_edited = st.data_editor(df)

df_edited.to_csv('test.csv', index=False)

I am noticing that I have to edit the dataframe twice for the changes to be reflected. I believe this is due to the code running top down every time an edit is detected, and I am not quite sure how to ensure that the edited dataframe would load up after saving.

I have tried using states and callbacks, but so far no luck.


Hi @Paul_Bezko,

Thanks for posting!

Try this option and let me know if it resolves.

1 Like

I’m experiencing the same issue. When reading CSV or JSON files, the changes are only saved after editing the st.data_editor twice. I attempted to use @tonykip’s solution, but it didn’t work. @Paul_Bezko, were you able to resolve this issue?

Here’s an update version using session state:

if 'df' not in st.session_state:
    st.session_state.df = pd.DataFrame(data=pd.read_csv("data/data.csv"))

edited_df = st.data_editor(st.session_state.df, use_container_width=True, hide_index=True)

edited_df.to_csv("data/data.csv", index=False)

It kinda works, but as soon as I leave the page and come back to it, the data_editor gets the value from the session_state and updates the csv with the old value.

1 Like