Welcome to the Streamlit community and thanks for your question!
The issue is that Streamlit reruns the script top-to-bottom on every interaction, so after opening the dialog, the code after example_dialog(file_path) continues immediately—before the user clicks “Ok” or “Cancel”. The dialog result (st.session_state[‘replace’]) is only set on the next rerun, so your file write logic is always too early.
To fix this, you need to separate the dialog display and the file writing into different script runs, using session state to track when to show the dialog and when to write the file. Here’s a pattern that works, based on community best practices and official docs:
import streamlit as st
from pathlib import Path
if "replace" not in st.session_state:
st.session_state['replace'] = None
if "pending_file" not in st.session_state:
st.session_state['pending_file'] = None
@st.dialog("Warning")
def example_dialog(file_path):
st.write(f"Le fichier : {file_path} existe, voulez-vous le remplacer ?")
if st.button("Ok"):
st.session_state['replace'] = True
st.rerun()
if st.button("Cancel"):
st.session_state['replace'] = False
st.rerun()
with st.expander("📤 Export (état actuel)", expanded=False):
filename = 'testn.txt'
current_dir = Path.cwd()
file_path = current_dir / filename
if st.button("Enregistrer le fichier dans ce dossier"):
if file_path.is_file():
st.session_state['pending_file'] = str(file_path)
st.session_state['replace'] = None
example_dialog(file_path)
else:
with open(file_path, "w") as f:
f.write('file does not exist')
st.success(f"New file : {file_path}")
# Handle dialog result after rerun
if st.session_state.get('pending_file') and st.session_state['replace'] is not None:
if st.session_state['replace']:
with open(st.session_state['pending_file'], "w") as f:
f.write('file exist')
st.success(f"Old file : {st.session_state['pending_file']}")
else:
st.info("File not overwritten.")
st.session_state['pending_file'] = None
st.session_state['replace'] = None
st.write(st.session_state)
This approach uses session state to remember the file and the user’s choice, and only writes the file after the dialog is closed and the script reruns. For more on this pattern, see this forum thread and the official st.dialog docs.
Sources: