Skip to content

Instantly share code, notes, and snippets.

@benlansdell
Last active April 18, 2024 16:52
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benlansdell/44000c264d1b373c77497c0ea73f0ef2 to your computer and use it in GitHub Desktop.
Save benlansdell/44000c264d1b373c77497c0ea73f0ef2 to your computer and use it in GitHub Desktop.
FilePicker for streamlit
"""FilePicker for streamlit.
Still doesn't seem to be a good solution for a way to select files to process from the server Streamlit is running on.
Here's a pretty functional solution.
Usage:
```
import streamlit as st
from filepicker import st_file_selector
tif_file = st_file_selector(st, key = 'tif', label = 'Choose tif file')
```
"""
import os
import streamlit as st
def update_dir(key):
choice = st.session_state[key]
if os.path.isdir(os.path.join(st.session_state[key+'curr_dir'], choice)):
st.session_state[key+'curr_dir'] = os.path.normpath(os.path.join(st.session_state[key+'curr_dir'], choice))
files = sorted(os.listdir(st.session_state[key+'curr_dir']))
files.insert(0, '..')
files.insert(0, '.')
st.session_state[key+'files'] = files
def st_file_selector(st_placeholder, path='.', label='Select a file/folder', key = 'selected'):
if key+'curr_dir' not in st.session_state:
base_path = '.' if path is None or path is '' else path
base_path = base_path if os.path.isdir(base_path) else os.path.dirname(base_path)
base_path = '.' if base_path is None or base_path is '' else base_path
files = sorted(os.listdir(base_path))
files.insert(0, '..')
files.insert(0, '.')
st.session_state[key+'files'] = files
st.session_state[key+'curr_dir'] = base_path
else:
base_path = st.session_state[key+'curr_dir']
selected_file = st_placeholder.selectbox(label=label,
options=st.session_state[key+'files'],
key=key,
on_change = lambda: update_dir(key))
selected_path = os.path.normpath(os.path.join(base_path, selected_file))
st_placeholder.write(os.path.abspath(selected_path))
return selected_path
@benlansdell
Copy link
Author

Works as follows:

Kapture 2022-09-15 at 14 35 05

@PeterLappo
Copy link

thanks, useful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment