Last active
September 12, 2020 00:17
-
-
Save thomasaarholt/b89b3f29ad82cd32176f2605834fa8ac to your computer and use it in GitHub Desktop.
ipywidgets file browser based on the Select widget. Single click folders to enter, click Load to load a file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ipywidgets as widgets | |
import os | |
from pathlib import Path | |
cwd = Path(os.getcwd()) | |
FOLDERLABEL = '-------FOLDERS-------' | |
FILESLABEL = '-------FILES-------' | |
def get_folder_contents(folder): | |
'Gets contents of folder, sorting by folder then files, hiding hidden things' | |
folder = Path(folder) | |
folders = [item.name for item in folder.iterdir() if item.is_dir() and not item.name.startswith('.')] | |
files = [item.name for item in folder.iterdir() if item.is_file() and not item.name.startswith('.')] | |
return [FOLDERLABEL] + sorted(folders) + [FILESLABEL] + sorted(files) | |
def go_to_address(address): | |
address = Path(address) | |
if address.is_dir(): | |
address_field.value = str(address) | |
select.unobserve(selecting, names='value') | |
select.options = get_folder_contents(folder=address) | |
select.observe(selecting, names='value') | |
select.value = None | |
def newaddress(value): | |
go_to_address(address_field.value) | |
def selecting(value): | |
if value['new'] and value['new'] not in [FOLDERLABEL, FILESLABEL]: | |
path = Path(address_field.value) | |
newpath = path / value['new'] | |
if newpath.is_dir(): | |
go_to_address(newpath) | |
elif newpath.is_file(): | |
#some other condition | |
pass | |
def parent(value): | |
new = Path(address_field.value).parent | |
go_to_address(new) | |
def load(value): | |
filepath = path / value['new'] | |
# load using your favourite python software! | |
address_field = widgets.Text(value=str(cwd)) | |
up_button = widgets.Button(description='Up') | |
select = widgets.Select(options=get_folder_contents(cwd), rows=15, value=None) | |
load_button = widgets.Button(description='Load') | |
box = widgets.HBox([widgets.VBox([address_field, select]), widgets.VBox([up_button, load_button])]) | |
select.observe(selecting, names='value') | |
up_button.on_click(parent) | |
load_button.observe(load) | |
address_field.on_submit(newaddress) | |
box |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Comments are very welcome