Hello
I want to check if a file exists before ovewriting it. I tried a dialog but the code continue before the dialog is closed. In the example, the dialog opens correcttly but the text “File exists’ appears wright away and the file is not written since the key “‘replace’ is False’ . After I click the ‘OK button’ the key 'replace is True but it is too late.
import streamlit as st
from pathlib import Path
if "replace" not in st.session_state:
st.session_state['replace'] = False
@st.dialog("Warning")
def example_dialog(some_arg: str):
st.write(f"Le fichier : {some_arg} existe, voulez-vous le remplcer ? ")
if st.button("Ok"):
print('Ok press')
st.session_state['replace'] = True
st.rerun()
if st.button("Cancel"):
st.rerun()
with st.expander("📤 Export (état actuel)", expanded=False):
filename = 'testn.txt'
current_dir = Path(__file__).resolve().parent if "__file__" in locals() else Path.cwd()
if st.button("Enregistrer le fichier dans ce dossier"):
Path(current_dir).mkdir(parents=True, exist_ok=True)
file_path = Path(current_dir) / filename
st.session_state['replace'] = False
if file_path.is_file():
example_dialog(file_path)
st.write('FIle exists')
if st.session_state['replace']:
with open(file_path, "w") as f:
f.write('file exist')
st.success(f"Old file : {file_path}")
st.session_state['replace'] = False
else:
with open(file_path, "w") as f:
f.write('file does not exist')
st.success(f"New file : {file_path}")
st.write(st.session_state)
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: