You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用os模块实现Streamlit中文件列表默认折叠显示

解决Streamlit文件列表默认折叠的问题

要实现默认折叠的文件列表,直接用st.write显示列表无法达成需求,你可以使用Streamlit内置的st.expander组件,它支持默认折叠状态,点击后再展开内容。

修改后的代码

import os
import streamlit as st

# 创建默认折叠的expander,标题为文件夹名称
with st.expander("📁 1 docx-raw", expanded=False):
    filelist = []
    for root, dirs, files in os.walk("/home/lungsang/Desktop/levelpack-UI/content/A0/1 docx-raw"):
        for file in files:
            filename = os.path.join(root, file)
            filelist.append(filename)
    st.write(filelist)

关键说明

  • st.expander的参数expanded=False是核心,设置后组件默认处于折叠状态
  • 将文件列表的生成和显示逻辑放在with代码块内,内容就会被包裹在可折叠容器中
  • 点击expander标题即可展开查看完整文件列表,收起后页面会更整洁

内容的提问来源于stack exchange,提问作者lungsang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 12:15:42