0

I am trying to download a data frame from streamlit in the form of a csv file. However it is not able to download in the CSV form rather it is downloading in an object.I have to manually convert to csv to get my desire output.Below is the sample code:

import pandas as pd
import base64
import streamlit as st

X = pd.DataFrame({'A':["bad",  "good", "better",   "good", "better",   "good", "better",   "good", "better",   "bad",  "good", "better",   "good", "better",   "bad",  "good", "better",   "bad",  "good", "better",   "good", "better",   "bad"],
                   'B': [3803,  1062,   4862,   6356,   2171,   532,    6982,   891,    1961,   3631,   1626,   1507,   3069,   2793,   721,    4288,   1601,   1439,   5807,   5054,   2411,   2913,   3505],
                   'C': [1318,  2537,   2315,   4967,   4483,   1433,   529,    1262,   1583,   506,    2576,   289,    3740,   3087,   309,    3493,   1862,   2666,   1231,   1828,   4144,   3503,   3102]
})

if X is not None:
            csv_exp = X.to_csv(index=False)
            b64 = base64.b64encode(csv_exp.encode()).decode()  # some strings <-> bytes conversions necessary here
            href = f'<a href="data:file/csv;base64,{b64}">Download Predicted File</a>(right-click and save as csv**)'
  
            st.markdown(href, unsafe_allow_html=True)
Yogesh Govindan
  • 339
  • 2
  • 12

1 Answers1

2

I've run your code. When I click the link, I see it save as download.

enter image description here

I change it to download.csv during the saving process and it seems to work.

enter image description here

When I open up download it doesn't open in my csv viewer.
When I open up download.csv it does open in my csv viewer.

When I run cat download and cat download.csv the outputs are identical and are in csv format. So the data is identical.

It seems that what you want is a way to create a default file name with .csv in it.

Here's a modified version of your csv download button that does that.

def st_pandas_to_csv_download_link(_df:pd.DataFrame, file_name:str = "dataframe.csv"): 
    csv_exp = _df.to_csv(index=False)
    b64 = base64.b64encode(csv_exp.encode()).decode()  # some strings <-> bytes conversions necessary here
    href = f'<a href="data:file/csv;base64,{b64}" download="{file_name}" > Download Dataframe (CSV) </a>'
    st.markdown(href, unsafe_allow_html=True)

st_pandas_to_csv_download_link(X, file_name = "my_file.csv")

A change is made on the line with href = on it. I've added download= to the link to define a file name the download. I glanced it from this stack overflow thread

Conic
  • 998
  • 1
  • 11
  • 26