### Print Version Number
Source: https://github.com/crahan/ipyfilechooser/blob/master/ipyfilechooser_examples.ipynb
Imports the ipyfilechooser library and prints its installed version number.
```python
# Print the version number
import ipyfilechooser
ištpyfilechooser.__version__
```
--------------------------------
### Create and Display FileChooser Widget
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
Instantiates the FileChooser widget. Use basic usage for default settings or the full parameter example for customization. The selection can be read from properties like `selected_path`, `selected_filename`, `selected`, or `value` after user interaction.
```python
from ipyfilechooser import FileChooser
from ipywidgets import Layout
# Basic usage — opens in the current working directory
fc = FileChooser()
display(fc)
# Full parameter example
fc = FileChooser(
path='/home/user/datasets', # Initial directory
filename='results.csv', # Pre-filled filename
title='Choose an output file',
select_desc='Select', # Label on the first click
change_desc='Change', # Label after a selection is made
show_hidden=False, # Hide dot-files
select_default=True, # Pre-select path+filename immediately
dir_icon='\U0001F4C1 ',
dir_icon_append=False, # Prepend (not append) the icon
show_only_dirs=False, # Show both files and folders
filter_pattern=['*.csv', '*.tsv'], # Only list CSV/TSV files
sandbox_path='/home/user', # Restrict navigation to /home/user
layout=Layout(width='600px'), # Widget width
)
display(fc)
# Read the selection after the user clicks "Select"
print(fc.selected_path) # '/home/user/datasets'
print(fc.selected_filename) # 'results.csv'
print(fc.selected) # '/home/user/datasets/results.csv'
print(fc.value) # same as fc.selected (ValueWidget interface)
```
--------------------------------
### Get Selected Value
Source: https://github.com/crahan/ipyfilechooser/blob/master/ipyfilechooser_examples.ipynb
Retrieves the currently selected file or directory path from the FileChooser instance.
```python
# Get the selected value
fdialog.selected
```
--------------------------------
### Toggle Visibility of Hidden Files
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
Control the display of hidden files and directories (those starting with '.') using the `show_hidden` property. Setting this to `True` includes them in the listing; `False` hides them. The widget re-renders immediately upon change.
```python
fc = FileChooser('/home/user')
display(fc)
# Show dot-files
fc.show_hidden = True
# Hide dot-files again
fc.show_hidden = False
```
--------------------------------
### FileChooser.show_hidden
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
Toggles the visibility of hidden files and directories (those starting with a dot `.`). When set to `True`, hidden items are included in the listing; setting it to `False` hides them. This change immediately re-renders the widget.
```APIDOC
## FileChooser.show_hidden — Toggle hidden files
Controls whether files and directories whose names begin with `.` are included in the directory listing. Changing the property immediately re-renders the widget via `refresh()`.
```python
fc = FileChooser('/home/user')
display(fc)
# Show dot-files
fc.show_hidden = True
# Hide dot-files again
fc.show_hidden = False
```
```
--------------------------------
### FileChooser.rows
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
Gets or sets the number of rows displayed in the directory listing area of the widget. This property is useful for adjusting the widget's vertical size within a notebook layout.
```APIDOC
## FileChooser.rows — Set directory listing height
Gets or sets the number of rows displayed in the directory `Select` box. Useful for adjusting the widget's visual footprint inside a notebook.
```python
fc = FileChooser('/home/user')
fc.rows = 15 # Show 15 rows instead of the default 8
display(fc)
```
```
--------------------------------
### Initialize and Display FileChooser
Source: https://github.com/crahan/ipyfilechooser/blob/master/README.md
Instantiate and display the FileChooser widget. The initial path can be specified during creation.
```python
from ipyfilechooser import FileChooser
# Create and display a FileChooser widget
fc = FileChooser('/Users/crahan/FC demo')
display(fc)
```
--------------------------------
### Initialize FileChooser
Source: https://github.com/crahan/ipyfilechooser/blob/master/ipyfilechooser_examples.ipynb
Initializes a FileChooser instance with a specified path, filename, title, and options for showing hidden files, default selection, and folder-only mode.
```python
from ipyfilechooser import FileChooser
import os
# Create new FileChooser:
# Path: current directory
# File: test.txt
# Title: FileChooser example
# Show hidden files: no
# Use the default path and filename as selection: yes
# Only show folders: no
fdialog = FileChooser(
os.getcwd(),
filename='test.txt',
title='FileChooser example',
show_hidden=False,
select_default=True,
show_only_dirs=False
)
display(fdialog)
```
--------------------------------
### FileChooser.__init__
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
Instantiates the FileChooser widget. It can be configured with various parameters to control its appearance and behavior, such as the initial path, filename, title, and filtering options. The widget defaults to the current working directory if no path is provided.
```APIDOC
## FileChooser.__init__
### Description
Instantiates the widget with sensible defaults. All parameters are optional; the dialog opens to `os.getcwd()` when no path is provided. Pass `select_default=True` to pre-select the default path/filename without user interaction. Raises `ParentPathError` if the initial `path` falls outside `sandbox_path`, and `InvalidFileNameError` if `filename` contains illegal characters (`/`, `..`, or the platform alternative separator).
### Method
```python
FileChooser(
path=None,
filename=None,
title=None,
select_desc='Select',
change_desc='Change',
show_hidden=False,
select_default=False,
dir_icon='\U0001F4C1 ',
dir_icon_append=False,
show_only_dirs=False,
filter_pattern=None,
sandbox_path=None,
layout=None
)
```
### Parameters
#### Path Parameters
- **path** (str) - Optional - Initial directory to open.
- **filename** (str) - Optional - Pre-filled filename.
- **title** (str) - Optional - HTML title for the dialog.
- **select_desc** (str) - Optional - Label on the first click.
- **change_desc** (str) - Optional - Label after a selection is made.
- **show_hidden** (bool) - Optional - Whether to show hidden files (files starting with '.'). Defaults to False.
- **select_default** (bool) - Optional - Whether to pre-select the default path/filename immediately. Defaults to False.
- **dir_icon** (str) - Optional - Icon to use for directories.
- **dir_icon_append** (bool) - Optional - Whether to append the icon to the directory name. Defaults to False.
- **show_only_dirs** (bool) - Optional - Whether to only show directories. Defaults to False.
- **filter_pattern** (list[str]) - Optional - List of fnmatch patterns to filter files.
- **sandbox_path** (str) - Optional - Restrict navigation to this path and its subdirectories.
- **layout** (ipywidgets.Layout) - Optional - Layout for the widget.
### Request Example
```python
from ipyfilechooser import FileChooser
from ipywidgets import Layout
# Basic usage
fc = FileChooser()
# Full parameter example
fc = FileChooser(
path='/home/user/datasets',
filename='results.csv',
title='Choose an output file',
select_desc='Select',
change_desc='Change',
show_hidden=False,
select_default=True,
dir_icon='\U0001F4C1 ',
dir_icon_append=False,
show_only_dirs=False,
filter_pattern=['*.csv', '*.tsv'],
sandbox_path='/home/user',
layout=Layout(width='600px')
)
```
### Response
#### Success Response (200)
- **selected_path** (str) - The selected directory path.
- **selected_filename** (str) - The selected filename.
- **selected** (str) - The full path to the selected file or directory.
- **value** (str) - Alias for `selected`.
```
--------------------------------
### Enable Folder-Selection Mode
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
Configure the widget for directory selection only by setting `show_only_dirs=True`. In this mode, the filename text box is hidden, and only directories can be selected. `selected_filename` will be empty, and `selected`/`selected_path` will point to the chosen folder.
```python
fc = FileChooser(
path='/home/user',
show_only_dirs=True,
title='Select output folder'
)
display(fc)
# After the user picks a folder:
print(fc.selected_path) # '/home/user/output'
print(fc.selected_filename) # ''
print(fc.selected) # '/home/user/output'
```
--------------------------------
### Enable Folder-Only Mode
Source: https://github.com/crahan/ipyfilechooser/blob/master/README.md
Configure the FileChooser to only allow selection of directories by setting `show_only_dirs` to True.
```python
# Switch to folder-only mode
fc.show_only_dirs = True
```
--------------------------------
### Switch to Folder-Only Mode
Source: https://github.com/crahan/ipyfilechooser/blob/master/ipyfilechooser_examples.ipynb
Configures the FileChooser to only allow the selection of directories, hiding all files.
```python
# Switch to folder-only mode
fdialog.show_only_dirs = True
```
--------------------------------
### Set Default Path and Filename
Source: https://github.com/crahan/ipyfilechooser/blob/master/README.md
Configure the default path and filename for the FileChooser. These defaults are used when the dialog is reset.
```python
# Change defaults and reset the dialog
fc.default_path = '/Users/crahan/'
fc.default_filename = 'output.txt'
fc.reset()
```
--------------------------------
### Set Multiple File Filter Patterns
Source: https://github.com/crahan/ipyfilechooser/blob/master/README.md
Apply multiple file filter patterns to restrict displayed files. Provide a list of `fnmatch` compatible patterns.
```python
# Set multiple file filter patterns (uses https://docs.python.org/3/library/fnmatch.html)
fc.filter_pattern = ['*.jpg', '*.png']
```
--------------------------------
### Set Multiple File Filter Patterns
Source: https://github.com/crahan/ipyfilechooser/blob/master/ipyfilechooser_examples.ipynb
Applies multiple filter patterns to display files matching any of the specified patterns (e.g., ['*.jpg', '*.png']).
```python
# Set multiple file filter patterns (uses https://docs.python.org/3/library/fnmatch.html)
fdialog.filter_pattern = ['*.jpg', '*.png']
```
--------------------------------
### FileChooser API Properties and Methods
Source: https://github.com/crahan/ipyfilechooser/blob/master/README.md
Lists available properties and methods for interacting with the FileChooser widget, including reset, refresh, and configuration options.
```python
fc.reset()
fc.refresh()
fc.register_callback(function_name)
fc.show_hidden
fc.dir_icon
fc.dir_icon_append
fc.show_only_dirs
fc.rows
fc.title
fc.filter_pattern
fc.default
fc.default_path
fc.default_filename
fc.sandbox_path
fc.value
fc.selected
fc.selected_path
fc.selected_filename
```
--------------------------------
### FileChooser.sandbox_path
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
Restricts filesystem navigation to a specified directory and its subdirectories. Users cannot navigate above the `sandbox_path`. This can be set during initialization or updated later. Setting it to a path that does not contain the current default path will raise a `ParentPathError`.
```APIDOC
## FileChooser.sandbox_path — Restrict filesystem navigation
Setting `sandbox_path` prevents the user from navigating above the specified directory. The path list dropdown is clipped to show only paths within the sandbox. Can be set at construction time or assigned as a property after creation (triggers an internal `reset()`). Raises `ParentPathError` if the current default path is outside the new sandbox.
```python
fc = FileChooser(
path='/home/user/projects',
sandbox_path='/home/user' # Users cannot navigate to /home or /
)
display(fc)
# Update sandbox dynamically
fc.sandbox_path = '/home/user/projects' # Tighten the restriction
# Attempting to navigate above sandbox raises ParentPathError:
try:
fc.sandbox_path = '/etc' # default_path '/home/user/projects' is not under '/etc'
except Exception as e:
print(e) # '/home/user/projects is not a part of /etc'
```
```
--------------------------------
### Switch Back to Standard Mode
Source: https://github.com/crahan/ipyfilechooser/blob/master/ipyfilechooser_examples.ipynb
Reverts the FileChooser to its standard mode, allowing both files and directories to be selected.
```python
# Switch back to standard mode
fdialog.show_only_dirs = False
```
--------------------------------
### Restrict Filesystem Navigation with sandbox_path
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
Limit user navigation to a specific directory using `sandbox_path`. Setting this property prevents users from browsing above the specified path. An error is raised if the current default path is outside the new sandbox.
```python
fc = FileChooser(
path='/home/user/projects',
sandbox_path='/home/user' # Users cannot navigate to /home or /
)
display(fc)
# Update sandbox dynamically
fc.sandbox_path = '/home/user/projects' # Tighten the restriction
# Attempting to navigate above sandbox raises ParentPathError:
try:
fc.sandbox_path = '/etc' # default_path '/home/user/projects' is not under '/etc'
except Exception as e:
print(e) # '/home/user/projects is not a part of /etc'
```
--------------------------------
### Change Default Path and Filename
Source: https://github.com/crahan/ipyfilechooser/blob/master/ipyfilechooser_examples.ipynb
Sets a new default directory and filename to be pre-selected when the FileChooser is initialized or reset.
```python
# Change the default path and filename
fdialog.default_path = os.path.abspath(os.path.join(os.getcwd(), '..'))
fdialog.default_filename = 'foobar.txt'
```
--------------------------------
### FileChooser.default / FileChooser.default_path / FileChooser.default_filename
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
Inspect and update the default path and filename. `default` is read-only, while `default_path` and `default_filename` are read/write and update the widget immediately.
```APIDOC
## FileChooser.default / FileChooser.default_path / FileChooser.default_filename
### Description
Inspect and update defaults. `default` (read-only) returns the joined default path and filename. `default_path` and `default_filename` are read/write properties; assigning them updates the widget form immediately without clearing an existing selection.
### Usage
```python
fc = FileChooser('/tmp', 'draft.txt')
# Inspect defaults
print(fc.default) # '/tmp/draft.txt'
print(fc.default_path) # '/tmp'
print(fc.default_filename) # 'draft.txt'
# Update defaults without resetting selection
fc.default_path = '/tmp/output'
fc.default_filename = 'final.txt'
print(fc.default) # '/tmp/output/final.txt'
```
```
--------------------------------
### Restrict Navigation with Sandbox Path
Source: https://github.com/crahan/ipyfilechooser/blob/master/README.md
Limit the user's navigation within the file system to a specified directory using the `sandbox_path` property.
```python
# Restrict navigation to /Users
fc.sandbox_path = '/Users'
```
--------------------------------
### String Representation
Source: https://github.com/crahan/ipyfilechooser/blob/master/ipyfilechooser_examples.ipynb
Obtains the string representation of the FileChooser instance, which typically shows the current selection.
```python
# String representation
print(fdialog)
```
--------------------------------
### FileChooser.show_only_dirs
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
Enables a folder-selection mode by hiding and disabling the filename text box. In this mode, only directories can be selected. The `selected_filename` property will be an empty string, and both `selected` and `selected_path` will point to the chosen directory.
```APIDOC
## FileChooser.show_only_dirs — Folder-selection mode
When `True`, the filename text box is hidden and disabled; the user can only select a directory. The `selected_filename` property will be an empty string and `selected` / `selected_path` both point to the chosen folder.
```python
fc = FileChooser(
path='/home/user',
show_only_dirs=True,
title='Select output folder'
)
display(fc)
# After the user picks a folder:
print(fc.selected_path) # '/home/user/output'
print(fc.selected_filename) # ''
print(fc.selected) # '/home/user/output'
```
```
--------------------------------
### FileChooser.title
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
Set an HTML string to display a title above the widget. An empty string hides the title. Useful for dynamic status messages.
```APIDOC
## FileChooser.title
### Description
Display an HTML title above the widget. Accepts an HTML string. Set to an empty string `''` to hide the title element entirely. Commonly used inside callbacks to provide dynamic status messages.
### Usage
```python
fc = FileChooser('/home/user')
fc.title = 'Select a configuration file'
# To hide the title:
# fc.title = ''
```
```
--------------------------------
### Customize Folder Icon
Source: https://github.com/crahan/ipyfilechooser/blob/master/ipyfilechooser_examples.ipynb
Configures the folder icon to use the system's path separator and appends it to the folder name.
```python
# Change folder icon to `os.sep` and append it to the folder name
fdialog.dir_icon = os.sep
fdialog.dir_icon_append = True
```
--------------------------------
### Reset FileChooser with Specific Path and Filename
Source: https://github.com/crahan/ipyfilechooser/blob/master/README.md
Reset the FileChooser to a specific path and filename using a shorthand method.
```python
# Shorthand reset
fc.reset(path='/Users/crahan/', filename='output.txt')
```
--------------------------------
### Restrict Navigation
Source: https://github.com/crahan/ipyfilechooser/blob/master/ipyfilechooser_examples.ipynb
Limits the user's navigation within the file system to a specific directory and its subdirectories.
```python
# Restrict navigation
fdialog.sandbox_path = '/Users/jdoe'
```
--------------------------------
### FileChooser.register_callback
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
Registers a callable function that is executed automatically whenever the user confirms a file selection. This callback receives the FileChooser instance as an argument, allowing access to its properties. Only one callback can be active at a time; subsequent calls will replace the existing one.
```APIDOC
## FileChooser.register_callback — Execute a function after selection
Registers a callable that is invoked automatically every time the user confirms a selection by clicking the Select/Change button. The callback receives the `FileChooser` instance as its sole argument, giving it full access to all widget properties. Only one callback can be registered at a time; calling this method again replaces the previous callback.
```python
fc = FileChooser('/home/user/data')
display(fc)
def on_file_selected(chooser):
path = chooser.selected
if path and path.endswith('.csv'):
chooser.title = f'CSV ready: {chooser.selected_filename}'
else:
chooser.title = 'Please select a .csv file'
fc.register_callback(on_file_selected)
```
```
--------------------------------
### Set or Change Title
Source: https://github.com/crahan/ipyfilechooser/blob/master/ipyfilechooser_examples.ipynb
Updates the title displayed in the FileChooser dialog.
```python
# Set or change the title
fdialog.title = 'Select the output file'
```
--------------------------------
### Refresh FileChooser Directory Listing
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
Forces the widget to re-read the current directory from disk and update the file list. This is useful when files are added or removed programmatically while the widget is displayed.
```python
import time
fc = FileChooser('/tmp')
display(fc)
# Simulate external file creation, then refresh the listing
open('/tmp/new_file.txt', 'w').close()
time.sleep(0.5)
fc.refresh()
```
--------------------------------
### FileChooser.selected / FileChooser.value
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
These properties provide the fully joined path of the selected file or directory. They return `None` if no selection has been confirmed yet. The `value` property is an alias compatible with `interact()` from `ipywidgets`.
```APIDOC
## FileChooser.selected / FileChooser.value — Read the chosen filepath
Both properties return the fully joined `os.path.join(selected_path, selected_filename)` string, or `None` when nothing has been confirmed yet. `value` is the `ValueWidget`-compatible alias used by `interact()`.
```python
from ipywidgets import interact
from ipyfilechooser import FileChooser
fc = FileChooser('/home/user', select_default=True)
# Use with interact — value is passed as the argument
def process(file_path):
if file_path:
print(f'Processing: {file_path}')
else:
print('No file selected yet.')
interact(process, file_path=fc)
```
```
--------------------------------
### Inspect and Update FileChooser Defaults
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
Access the combined default path and filename, or individually update `default_path` and `default_filename`. Updates reflect immediately without clearing existing selections.
```python
fc = FileChooser('/tmp', 'draft.txt')
display(fc)
print(fc.default) # '/tmp/draft.txt'
print(fc.default_path) # '/tmp'
print(fc.default_filename) # 'draft.txt'
# Update defaults without resetting selection
fc.default_path = '/tmp/output'
fc.default_filename = 'final.txt'
print(fc.default) # '/tmp/output/final.txt'
```
--------------------------------
### Customize Dialog Title
Source: https://github.com/crahan/ipyfilechooser/blob/master/README.md
Set a custom title for the FileChooser dialog. An empty string will hide the title.
```python
# Change the title (use '' to hide)
fc.title = 'FileChooser title'
```
--------------------------------
### Register Callback for File Selection
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
Register a callable to be invoked when a file is selected. The callback receives the FileChooser instance and can update the widget's title based on the selection. Only one callback can be active at a time.
```python
fc = FileChooser('/home/user/data')
display(fc)
def on_file_selected(chooser):
path = chooser.selected
if path and path.endswith('.csv'):
chooser.title = f'CSV ready: {chooser.selected_filename}'
else:
chooser.title = 'Please select a .csv file'
fc.register_callback(on_file_selected)
```
--------------------------------
### Set File Filter Pattern
Source: https://github.com/crahan/ipyfilechooser/blob/master/ipyfilechooser_examples.ipynb
Applies a filter to display only files matching a specific pattern (e.g., '*.txt'). This uses Python's fnmatch module for pattern matching.
```python
# Set a file filter pattern (uses https://docs.python.org/3/library/fnmatch.html)
fdialog.filter_pattern = '*.txt'
```
--------------------------------
### Set and Update FileChooser Title
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
Set an HTML string for the widget's title. Set to an empty string to hide it. Commonly used in callbacks for dynamic status messages.
```python
fc = FileChooser('/home/user')c.title = 'Select a configuration file'
display(fc)
# Dynamically update the title from a callback
def on_select(chooser):
chooser.title = f'Selected: {chooser.selected_filename}'
fc.register_callback(on_select)
# Hide the title
fc.title = ''
```
--------------------------------
### Set Directory Listing Height
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
Adjust the number of rows displayed in the directory selection box using the `rows` property. This is useful for controlling the widget's visual space within a notebook.
```python
fc = FileChooser('/home/user')
fc.rows = 15 # Show 15 rows instead of the default 8
display(fc)
```
--------------------------------
### Access Selected File Information
Source: https://github.com/crahan/ipyfilechooser/blob/master/README.md
Retrieve the selected path, filename, or the combined filepath from the FileChooser widget.
```python
# Print the selected path, filename, or both
print(fc.selected_path)
print(fc.selected_filename)
print(fc.selected)
```
--------------------------------
### FileChooser.refresh
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
Forces the widget to re-read the current directory from disk and update the file listing. This is useful when files or directories have been changed externally while the widget is active.
```APIDOC
## FileChooser.refresh
### Description
Forces the widget to re-read the current directory from disk and repopulate the file list. Useful when files are created or deleted programmatically while the widget is open.
### Method
```python
refresh()
```
### Request Example
```python
import time
fc = FileChooser('/tmp')
# Simulate external file creation
open('/tmp/new_file.txt', 'w').close()
time.sleep(0.5)
# Refresh the listing
fc.refresh()
```
### Response
#### Success Response (200)
- **None** - This method does not return a value.
```
--------------------------------
### Filter Visible Files by Extension
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
Control which files are visible in the listing using `filter_pattern`. Accepts a single `fnmatch`-style pattern or a list of patterns. Matching is case-insensitive. Files not matching the pattern are hidden, and the Select button is disabled for non-matching filenames.
```python
fc = FileChooser('/home/user/images')
# Single pattern
fc.filter_pattern = '*.png'
# Multiple patterns
fc.filter_pattern = ['*.jpg', '*.jpeg', '*.png', '*.gif']
# Clear the filter
fc.filter_pattern = None
display(fc)
```
--------------------------------
### Handle FileChooser Custom Exceptions
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
Catch `ParentPathError`, `InvalidFileNameError`, and `InvalidPathError` for robust path and filename argument handling. These exceptions provide a descriptive `.message` attribute.
```python
from ipyfilechooser import FileChooser
from ipyfilechooser.errors import ParentPathError, InvalidFileNameError, InvalidPathError
# ParentPathError — path outside sandbox
try:
fc = FileChooser(path='/etc', sandbox_path='/home/user')
except ParentPathError as e:
print(f'ParentPathError: {e.message}')
# '/etc is not a part of /home/user'
# InvalidFileNameError — filename contains path separators or '..'
try:
fc = FileChooser(filename='../secret.txt')
except InvalidFileNameError as e:
print(f'InvalidFileNameError: {e.message}')
# '../secret.txt cannot contain ['/', '..']'
# InvalidPathError — raised internally by normalize_path for non-existent dirs
from ipyfilechooser.utils import normalize_path
try:
normalize_path('/nonexistent/path')
except InvalidPathError as e:
print(f'InvalidPathError: {e.message}')
# '/nonexistent/path does not exist'
```
--------------------------------
### FileChooser.dir_icon / FileChooser.dir_icon_append
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
Customizes the icons displayed next to directory names in the listing. `dir_icon` sets the string to be prepended or appended, while `dir_icon_append` (boolean) determines its position (before or after the name). Setting `dir_icon` to `None` removes icons.
```APIDOC
## FileChooser.dir_icon / FileChooser.dir_icon_append — Customize folder icons
`dir_icon` sets the string prepended (or appended) to every directory name in the listing. Set to `None` to show bare directory names. `dir_icon_append` controls whether the icon appears before (`False`, default) or after (`True`) the directory name.
```python
fc = FileChooser('/home/user')
display(fc)
# Use a plain slash instead of an emoji
fc.dir_icon = '/'
fc.dir_icon_append = True # e.g., "Documents/"
# Use a custom emoji
fc.dir_icon = '📂 '
fc.dir_icon_append = False # e.g., "📂 Documents"
# Remove icons entirely
fc.dir_icon = None
```
```
--------------------------------
### Register Callback Function
Source: https://github.com/crahan/ipyfilechooser/blob/master/ipyfilechooser_examples.ipynb
Registers a callback function to be executed when a selection is made or changed in the FileChooser. The callback receives the chooser instance as an argument.
```python
# Callback example
def change_title(chooser):
chooser.title = 'Callback function executed'
# Register callback function
fdialog.register_callback(change_title)
```
--------------------------------
### Register Callback Function
Source: https://github.com/crahan/ipyfilechooser/blob/master/README.md
Register a callback function to be executed when a selection is made or the dialog state changes. The callback receives the chooser instance as an argument.
```python
# Sample callback function
def change_title(chooser):
chooser.title = 'Callback function executed'
# Register callback function
fc.register_callback(change_title)
```
--------------------------------
### ParentPathError, InvalidPathError, InvalidFileNameError
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
Custom exception classes for handling errors related to path and filename arguments. All extend `Exception` and provide a descriptive `.message` attribute.
```APIDOC
## ParentPathError, InvalidPathError, InvalidFileNameError
### Description
Three custom exception classes signal misuse of path or filename arguments. All extend `Exception` and carry a descriptive `.message` attribute alongside the offending value.
### Usage
```python
from ipyfilechooser import FileChooser
from ipyfilechooser.errors import ParentPathError, InvalidFileNameError, InvalidPathError
from ipyfilechooser.utils import normalize_path
# ParentPathError — path outside sandbox
try:
fc = FileChooser(path='/etc', sandbox_path='/home/user')
except ParentPathError as e:
print(f'ParentPathError: {e.message}')
# Expected output: ParentPathError: /etc is not a part of /home/user
# InvalidFileNameError — filename contains path separators or '..'
try:
fc = FileChooser(filename='../secret.txt')
except InvalidFileNameError as e:
print(f'InvalidFileNameError: {e.message}')
# Expected output: InvalidFileNameError: ../secret.txt cannot contain ['/', '..']
# InvalidPathError — raised internally by normalize_path for non-existent dirs
try:
normalize_path('/nonexistent/path')
except InvalidPathError as e:
print(f'InvalidPathError: {e.message}')
# Expected output: InvalidPathError: /nonexistent/path does not exist
```
```
--------------------------------
### Set Single File Filter Pattern
Source: https://github.com/crahan/ipyfilechooser/blob/master/README.md
Filter the displayed files to match a specific pattern using `filter_pattern`. This uses Python's `fnmatch` module.
```python
# Set a file filter pattern (uses https://docs.python.org/3/library/fnmatch.html)
fc.filter_pattern = '*.txt'
```
--------------------------------
### Customize Appearance
Source: https://github.com/crahan/ipyfilechooser/blob/master/ipyfilechooser_examples.ipynb
Modifies the appearance of the FileChooser by controlling the visibility of hidden files, the number of rows displayed, and the folder icons.
```python
# Show hidden files, change rows to 10, and hide folder icons
fdialog.show_hidden = True
fdialog.rows = 10
fdialog.dir_icon = None
```
--------------------------------
### FileChooser.filter_pattern
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
Limits the files displayed in the directory listing based on provided `fnmatch`-style patterns. This can be a single pattern string or a list of patterns. Matching is case-insensitive. Files not matching any pattern will not be shown, and the Select button will be disabled for such files.
```APIDOC
## FileChooser.filter_pattern — Limit visible files by extension
Accepts a single `fnmatch`-style pattern string or a list of patterns. Matching is case-insensitive. When set, only files whose names match at least one pattern are shown in the directory listing and the Select button is disabled for filenames that do not match.
```python
fc = FileChooser('/home/user/images')
# Single pattern
fc.filter_pattern = '*.png'
# Multiple patterns
fc.filter_pattern = ['*.jpg', '*.jpeg', '*.png', '*.gif']
# Clear the filter
fc.filter_pattern = None
display(fc)
```
```
--------------------------------
### Integrate FileChooser with ipywidgets.interact
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
Use `get_interact_value` to integrate FileChooser with `ipywidgets.interact()` and `ipywidgets.interactive()`. This method returns `self.selected`.
```python
from ipywidgets import interactive, Button, VBox
from IPython.display import display
from ipyfilechooser import FileChooser
fc = FileChooser('/home/user/data', filter_pattern='*.json', select_default=False)
def load_json(file_path):
if file_path:
import json, pathlib
try:
data = json.loads(pathlib.Path(file_path).read_text())
print(f'Loaded {len(data)} top-level keys: {list(data.keys())}')
except Exception as e:
print(f'Error: {e}')
else:
print('No file selected.')
w = interactive(load_json, file_path=fc)
display(w)
```
--------------------------------
### Customize Folder Icons
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
Modify the icons displayed before or after directory names using `dir_icon` and `dir_icon_append`. Set `dir_icon` to a string (e.g., '/', '📂 ') or `None` to remove icons. `dir_icon_append=True` places the icon after the name.
```python
fc = FileChooser('/home/user')
display(fc)
# Use a plain slash instead of an emoji
fc.dir_icon = '/'
fc.dir_icon_append = True # e.g., "Documents/"
# Use a custom emoji
fc.dir_icon = '📂 '
fc.dir_icon_append = False # e.g., "📂 Documents"
# Remove icons entirely
fc.dir_icon = None
```
--------------------------------
### Control Visibility of Hidden Files
Source: https://github.com/crahan/ipyfilechooser/blob/master/README.md
Toggle the display of hidden files and directories in the FileChooser using the `show_hidden` property.
```python
# Change hidden files
fc.show_hidden = True
```
--------------------------------
### FileChooser.get_interact_value
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
Integrates with ipywidgets `interact()`. Returns `self.selected` (or `None`), satisfying the `ValueWidget` protocol for direct use with `ipywidgets.interact()` and `ipywidgets.interactive()`.
```APIDOC
## FileChooser.get_interact_value
### Description
Returns `self.selected` (or `None`). This method satisfies the `ValueWidget` protocol so `FileChooser` can be passed directly to `ipywidgets.interact()` and `ipywidgets.interactive()`.
### Usage
```python
from ipywidgets import interactive
from ipyfilechooser import FileChooser
fc = FileChooser('/home/user/data', filter_pattern='*.json', select_default=False)
def load_json(file_path):
if file_path:
# Process the selected file
print(f'Processing file: {file_path}')
else:
print('No file selected.')
w = interactive(load_json, file_path=fc)
# display(w) # In a notebook environment
```
```
--------------------------------
### Reset FileChooser
Source: https://github.com/crahan/ipyfilechooser/blob/master/ipyfilechooser_examples.ipynb
Resets the FileChooser to its default state, clearing any current selection and reverting to the initial path and filename.
```python
# Reset to defaults and clear the selected value
fdialog.reset()
```
--------------------------------
### Reset FileChooser Dialog
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
Clears the current selection and resets the dialog to its default path and filename. Can restore initial construction values or update defaults with new path/filename arguments. The `selected` property will be `None` after a reset until a new selection is made.
```python
fc = FileChooser('/tmp', 'old_output.txt')
display(fc)
# Restore original defaults (no arguments)
fc.reset()
# Override defaults inline — shorthand for updating default_path / default_filename
fc.reset(path='/tmp/archive', filename='new_output.txt')
# After reset, selected is None until the user clicks Select again
assert fc.selected is None
```
--------------------------------
### Read Chosen Filepath with interact
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
Access the selected filepath using the `selected` or `value` properties. The `value` property is compatible with `ipywidgets.interact`. The callback function receives the file path and prints a message indicating processing or if no file is selected.
```python
from ipywidgets import interact
from ipyfilechooser import FileChooser
fc = FileChooser('/home/user', select_default=True)
# Use with interact — value is passed as the argument
def process(file_path):
if file_path:
print(f'Processing: {file_path}')
else:
print('No file selected yet.')
interact(process, file_path=fc)
```
--------------------------------
### Customize Directory Icon
Source: https://github.com/crahan/ipyfilechooser/blob/master/README.md
Customize the icon used for directory entries. `dir_icon_append` controls whether the icon precedes or follows the directory name.
```python
# Customize dir icon
fc.dir_icon = '/'
fc.dir_icon_append = True
```
--------------------------------
### FileChooser.reset
Source: https://context7.com/crahan/ipyfilechooser/llms.txt
Resets the file chooser dialog to its default path and filename. This method can be called without arguments to restore the initial values set during instantiation, or with new path and filename arguments to update the defaults.
```APIDOC
## FileChooser.reset
### Description
Clears the current selection and returns the dialog to its default (or newly supplied) path and filename. Can be called with no arguments to restore the values provided at construction time, or with keyword arguments to update the defaults in place. Raises `ParentPathError` if the new path violates an active `sandbox_path`.
### Method
```python
reset(path=None, filename=None)
```
### Parameters
#### Path Parameters
- **path** (str) - Optional - The new default path to set.
- **filename** (str) - Optional - The new default filename to set.
### Request Example
```python
fc = FileChooser('/tmp', 'old_output.txt')
# Restore original defaults
fc.reset()
# Override defaults inline
fc.reset(path='/tmp/archive', filename='new_output.txt')
```
### Response
#### Success Response (200)
- **None** - This method does not return a value.
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.