eric
eric

Reputation: 8029

FileUpload ipywidget: how to specify initial directory?

I am using a FileUpload ipywidget in Jupyter, and want to specify the starting directory. Right now I have this:

import ipywidgets as widgets
my_widget = widgets.FileUpload(accept='.json', multiple=False)

After googling, and looking at the source code, I am not seeing how to specify the initial directory that will open when the user clicks the widget. On the workstations we use at work, things can be particularly labyrinthine so it will save a lot of time if I can add this as an argument.

I'm open to other simple options than using ipywidgets for exploring directories/loading files within Jupyter, but it does work very well generally.

If it matters, I'm in Windows 10.

Upvotes: 1

Views: 2255

Answers (1)

eric
eric

Reputation: 8029

There is no way to specify the starting directory using the FileUpload widget. This was verified by a developer of ipywidgets in an issue devoted to this topic. Instead, you can use a different custom widget, the FileChooser in the ipyfilechooser repo, to do what you want to do.

First, install with pip install ipyfilechooser.

Then in your notebook:

from ipyfilechooser import FileChooser

starting_directory = 'C:/foo'
chooser = FileChooser(starting_directory)
display(chooser)

To see some of the attributes you are most likely to use:

print(chooser.selected_filename)
print(chooser.selected)
print(chooser.selected_path)

There are many additional options discussed at the repository.

Of course, once you get the path to the filename that you care about (e.g., C:/foo/foo.json) then you will have to figure out the best way to open the file using the standard libraries for such things.

Upvotes: 3

Related Questions