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

在Streamlit中点击按钮后能否保存文本?如何将输出存为CSV?

实现点击按钮后保存内容到CSV文件

当然可以实现,只需要在按钮触发的逻辑里添加写入CSV的代码即可,以下是两种常见的实现方式:

方式一:使用pandas库(推荐)

先确保已安装pandas:pip install pandas,然后修改代码如下:

import streamlit as st
import pandas as pd

b0 = st.button("Hi There", key=0)
if b0:
    content = "gratitude word"
    st.write(content)
    # 将内容保存为CSV
    df = pd.DataFrame({"content": [content]})
    df.to_csv("file_one.csv", index=False, encoding="utf-8")
    st.success("文件已成功保存为file_one.csv")

方式二:使用Python内置csv模块

无需额外安装依赖,直接用标准库实现:

import streamlit as st
import csv

b0 = st.button("Hi There", key=0)
if b0:
    content = "gratitude word"
    st.write(content)
    # 将内容保存为CSV
    with open("file_one.csv", "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(["content"])  # 写入表头
        writer.writerow([content])    # 写入目标内容
    st.success("文件已成功保存为file_one.csv")

两种方式都会在点击按钮后,把"gratitude word"写入到file_one.csv文件中,文件会生成在你的Streamlit脚本所在的目录下。

内容的提问来源于stack exchange,提问作者アルサ

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 17:10:25