# https://discuss.streamlit.io/t/heres-a-download-function-that-works-for-dataframes-and-txt/4052 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() return f'{download_link_text}'