howdy, team!
I want my Streamlit app to cache local metadata into a file which may need initially created/“touched”.
Following e.g. W3Schools file initialization works for non-Streamlit Python programs:
f = open("myfile.txt", "w")
However, within Streamlit, this code sometimes works but lately has been erring more than not even with the various (should not be needed) workarounds I’ve been adding on top:
import os
import streamlit as st
def put(file, data):
if not os.path.exists(file):
# open(file,'x')
open(file,'w+')
with open(file,'r+') as ff:
fd = ff.read()
if fd != data:
with open(file,'w+') as ff:
ff.write(data)
where example function call on Mac:
put("/Users/me/Documents/_cached.json", "test")
Streamlit errors
FileNotFoundError: [Errno 2] No such file or directory: '/Users/me/Documents/_cached.json'
with Traceback rooting in:
File "/Users/me/Documents/home.py", line 447, in put_cache
F.put(f"/Users/me/documents/files.py",data)
File "/Users/me/documents/files.py", line 66, in put
open(f,'w+')
I confirm when this error occurs, the file does not initialize within that directory, but I want it to AND infrequently it does.
Evidence this code does work in Python outside Streamlit:
$ ipython
Python 3.11.6 (main, Oct 2 2023, 20:46:14) [Clang 14.0.3 (clang-1403.0.22.14.1)]
IPython 8.14.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: import os
In [2]: def put(file, data):
...: if not os.path.exists(file):
...: # open(file,'x')
...: open(file,'w+')
...:
...: with open(file,'r+') as ff:
...: fd = ff.read()
...:
...: if fd != data:
...: with open(file,'w+') as ff:
...: ff.write(data)
...:
In [3]: put("/Users/me/Downloads/_cached.json", "test")
In [4]: exit
$ pwd
/Users/me/Downloads
$ ls | grep cached
_cached.json
Anytime code sometimes-works-sometimes-errors I default guess race-condition, but I’m failing to see how that might apply in this situation so wanted to ask the experts. I did not find historically similar, but please link if I had poor search foo and my question is a duplicate.
TIA!
- Local (Mac Sonoma 14.1.1 with Firefox 120.0)
- NA
- Private (and above question is privacy redacted, please discount any typos)
- ✓
- Streamlit and Python versions:
$ python --version Python 3.11.6 $ streamlit --version Streamlit, version 1.28.2