简体   繁体   中英

How to download various data from Streamlit to HDF5 file with `st.download_button`?

How can I download various numpy arrays in one .h5 file from a Streamlit application?

The h5py library makes you create a h5py.File before attaching any datasets to it. In the Streamlit environment you cannot create files, so how could I save something to this file format?

This can be done by the intermediary of a temporary 'fake' file of type io.BytesIO , which Streamlit can handle and save to file using the st.download_button component.

Let's say you have 2 numpy arrays to save to your HDF5 file:

import io
import h5py
import numpy as np
import streamlit

def prepare_bytes():
    bio = io.BytesIO()

    with h5py.File(bio, 'w') as f:
        f['array_1'] = np.array([1, 2, 3, 4])
        f['array_2'] = np.array([[1, 2], [3, 4]])

    return bio

st.streamlit.download_button(
    'Download as HDF5', data=prepare_bytes(),
    file_name='data.h5', mime='application/x-hdf5'
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM