我可以使用 Streamlit 选择文件夹吗?
file_uploader 允许选择文件,但不能选择文件夹。
我无法在 Streamlit 中使用 file_uploader 选择目录。但我想将数据框保存到用户决定的文件夹中。如果有办法做到这一点,如果你告诉我,我会很高兴。
小智 1
Streamlitfile_uploader本身尚不支持目录选择。
这是将文件保存在用户指定的目录中的解决方法。这里我们允许用户以字符串形式输入目录路径。
import streamlit as st
import pandas as pd
import os
def save_df_to_folder(df, folder_path, file_name):
"""Saves dataframe to the provided folder."""
if not os.path.isdir(folder_path):
st.error('The provided folder does not exist. Please provide a valid folder path.')
return
file_path = os.path.join(folder_path, file_name)
df.to_csv(file_path, index=False)
st.success(f'Successfully saved dataframe to {file_path}')
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}) # example dataframe
folder_path = st.text_input('Enter the folder path where you want to save the dataframe:')
file_name = st.text_input('Enter the filename for the dataframe (should end in .csv):')
if st.button('Save Dataframe'):
save_df_to_folder(df, folder_path, file_name)
Run Code Online (Sandbox Code Playgroud)
它看起来是这样的:
让我知道是否有帮助!:)
查理