File browser to select a folder or a file

I need to be able to browse the file system to be able to select a directory or a file for purposes other than uploading files. In fact the UI that is presented when the “Browse” button is pressed in the file_uploader component is exactly what I need. Is there a component available or a built in function that can be used for this?

Thanks.

Hi @TPMStreamer

Here’s a code snippet from @Adrien_Treuille that allows you to browse through files on the server using the st.selectdown() widget:

import streamlit as st
import os

def file_selector(folder_path='.'):
    filenames = os.listdir(folder_path)
    selected_filename = st.selectbox('Select a file', filenames)
    return os.path.join(folder_path, selected_filename)

filename = file_selector()
st.write('You selected `%s`' % filename)

Thanks for your reply. I guess I didn’t describe what I need quite right. If you look at the UI that is presented when you click the “Browse Files” button on the file_uploader widget, that is precisely what I need. It brings up the native file selection UI (at least on my Mac it does).

I don’t need any files to be uploaded, nor do I need the selected files to be displayed anywhere.

Specifically the browser will have two modes… file selection or folder selection. In file mode,
the browser will return the list of files selected. If a folder is selected while in file mode, the folder is opened to display it’s contents. In folder mode, only directories would be displayed and the path of the selected directory would be returned.

Going into this I assumed this standard UI feature would be built in so I kind of put off implementing it until late in the dev cycle. Now it has turned out to be the most challenging task yet. There’s a good chance that my unfamiliarity with streamlit and python is the root cause of all my problems.

Are you able to rectify this?

You can integrate other python libraries.
I used wxPython to create DirDialog when st.button is clicked.
need to pip install wx if don’t have it yet.

import wx

if st.button(“Browse”):
dialog = wx.DirDialog(None, “Select a folder:”, style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
if dialog.ShowModal() == wx.ID_OK:
folder_path = dialog.GetPath() # folder_path will contain the path of the folder you have selected as string

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.