If it helps anyone, I posted a version of the function that can handle both dataframes and text: Here's a download function that works for dataframes and txt (posted below for reference)
Also, curious if anyone has any ideas about how to generalize file downloads in Streamlit. For example: CSV, Excel, img, txt, midi, pdf, video formats, etc.
It would also be neat to auto download on button click - or interaction with another Streamlit component - rather than a link being returned. I’ve started researching ways to achieve this, but it’s admittedly not my specialty area. Any thoughts on how to achieve this?
import base64
import streamlit as st
import pandas as pd
def download_link(object_to_download, download_filename, download_link_text):
"""
Generates a link to download the given object_to_download.
object_to_download (str, pd.DataFrame): The object to be downloaded.
download_filename (str): filename and extension of file. e.g. mydata.csv, some_txt_output.txt
download_link_text (str): Text to display for download link.
Examples:
download_link(YOUR_DF, 'YOUR_DF.csv', 'Click here to download data!')
download_link(YOUR_STRING, 'YOUR_STRING.txt', 'Click here to download your text!')
"""
if isinstance(object_to_download,pd.DataFrame):
object_to_download = object_to_download.to_csv(index=False)
# some strings <-> bytes conversions necessary here
b64 = base64.b64encode(object_to_download.encode()).decode()