Streamlit项目加载本地CSS遇FileNotFoundError问题求助
问题:Streamlit加载本地CSS文件报错FileNotFoundError
我在Streamlit项目中尝试加载本地CSS文件时,一直报错:
FileNotFoundError: [Errno 2] No such file or directory: 'style/style.css'
我的目录结构是:brookfield.py 同目录下创建了style文件夹,里面用Windows记事本创建了style.css文件。加载代码如下:
#---- USE LOCAL CSS ---- def local_css(file_name): with open(file_name) as f: st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True) local_css("style/style.css")
完整回溯信息:
Traceback: File "C:\Users\Ronmi\Anaconda3\lib\site-packages\streamlit\scriptrunner\script_runner.py", line 557, in _run_script exec(code, module.__dict__) File "brookfield.py", line 33, in <module> local_css("style/style.css") File "brookfield.py", line 30, in local_css with open(file_name) as f:
确认目录结构看似正常,求解决方法。
解决方法
检查Streamlit工作目录
运行Streamlit时,它的工作目录可能并非brookfield.py所在目录。在代码开头添加以下代码打印当前工作目录:import os print("Current working directory:", os.getcwd())如果输出目录不是脚本所在目录,要么切换到该目录后再执行
streamlit run brookfield.py,要么改用绝对路径加载CSS。使用绝对路径加载CSS
利用__file__变量获取脚本绝对路径,拼接出CSS文件的完整路径,避免相对路径的歧义:import os def local_css(file_name): script_dir = os.path.dirname(os.path.abspath(__file__)) css_path = os.path.join(script_dir, file_name) with open(css_path) as f: st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True) local_css("style/style.css")排查Windows隐藏扩展名问题
Windows记事本默认会隐藏已知文件扩展名,你创建的文件可能实际是style.css.txt,只是显示为style.css。打开文件夹选项,取消勾选“隐藏已知文件类型的扩展名”,确认文件真实名称。检查文件读取权限
右键style.css文件选择“属性”,在“安全”选项卡中确认当前用户拥有该文件的读取权限,避免因权限不足导致无法读取。
内容的提问来源于stack exchange,提问作者user22294643
相关产品推荐
相关产品推荐

