File Input

#| '!! shinylive warning !!': |
#|   shinylive does not work in self-contained HTML documents.
#|   Please set `embed-resources: false` in your metadata.
#| standalone: true
#| components: [viewer]
#| viewerHeight: 200

from shiny import App, render, ui

app_ui = ui.page_fluid(
    ui.input_file("f", "Pick a file, any file"),
    "Input file data:",
    ui.output_text("txt"),
)

def server(input, output, session):
    @render.text
    def txt():
        return input.f()

app = App(app_ui, server)
from shiny import reactive
from shiny.express import input, render, ui

ui.input_file("f", "Pick a file, any file")  
"Input file data:"

@render.text
def txt():
    return input.f()  
from shiny import App, render, ui

app_ui = ui.page_fluid(
    ui.input_file("f", "Pick a file, any file"),  
    "Input file data:",
    ui.output_text("txt"),
)

def server(input, output, session):
    @render.text
    def txt():
        return input.f()  

app = App(app_ui, server)
No matching items

Relevant Functions

  • ui.input_file
    ui.input_file(id, label, *, multiple=False, accept=None, width=None, button_label='Browse...', placeholder='No file selected', capture=None)

  • express.ui.input_file
    express.ui.input_file(id, label, *, multiple=False, accept=None, width=None, button_label='Browse...', placeholder='No file selected', capture=None)

No matching items

Details

A file input allows you to upload one or more files.

To add a file input to your app:

  1. Add ui.input_file() to the UI of your app to create a file upload component. Where you call this function will determine where the date selector will appear within the app’s layout.

  2. Specify the id and label parameters of ui.input_date() to define the identifier and label of the file upload. ui.input_file() also includes various optional parameters to control what kinds of files can be uploaded.

The value of an input component is accessible as a reactive value within the server() function. The file input returns a list containing a dictionary of 4 keys:

  1. Use input.<file_id>() to access the value of the file input (e.g., input.file()). The server value of of the file input is a list containing a dictionary.

Here is an example of what the file input returns:

[{'name': 'my_file.csv', 'size': 525600, 'type': 'text/csv', 'datapath': '/tmp/fileupload-8khw0q6n/tmpeobuc_pj/0.csv'}]

You will typically want to load the uploaded in your application, to access the path of the uploaded file, you will first need to get the dictionary from the list, and get the value from the 'datapath' key. For example, input.<file_id>()[0]['datapath'].

Read a CSV file into pandas

You can limit the data type to only CSV files that can be read into pandas.

#| '!! shinylive warning !!': |
#|   shinylive does not work in self-contained HTML documents.
#|   Please set `embed-resources: false` in your metadata.
#| standalone: true
#| components: [viewer]
#| viewerHeight: 300

import pandas as pd
from shiny import App, reactive, render, ui

app_ui = ui.page_fluid(
    ui.input_file(
        "input_file", "Choose CSV File", accept=[".csv"], multiple=False
    ),
    ui.input_checkbox_group(
        "stats",
        "Summary Stats",
        choices=["Row Count", "Column Count", "Column Names"],
        selected=["Row Count", "Column Count", "Column Names"],
    ),
    ui.output_data_frame("summary"),
)

def server(input, output, session):
    @reactive.calc
    def parsed_file():
        file = input.input_file()
        if file is None:
            return pd.DataFrame()
        return pd.read_csv(file[0]["datapath"])

    @render.data_frame
    def summary():
        df = parsed_file()

        if df.empty:
            return pd.DataFrame()

        # Get the row count, column count, and column names of the DataFrame
        row_count = df.shape[0]
        column_count = df.shape[1]
        names = df.columns.tolist()
        column_names = ", ".join(str(name) for name in names)

        # Create a new DataFrame to display the information
        info_df = pd.DataFrame({
            "Row Count": [row_count],
            "Column Count": [column_count],
            "Column Names": [column_names],
        })

        # input.stats() is a list of strings; subset the columns based on the selected
        # checkboxes
        return info_df.loc[:, input.stats()]

app = App(app_ui, server)
import pandas as pd
from shiny import reactive
from shiny.express import input, render, ui
from shiny.types import FileInfo

ui.input_file("input_file", "Choose CSV File", accept=[".csv"], multiple=False)
ui.input_checkbox_group(
    "stats",
    "Summary Stats",
    choices=["Row Count", "Column Count", "Column Names"],
    selected=["Row Count", "Column Count", "Column Names"],
)

@reactive.calc
def parsed_file():
    file = input.input_file()
    if file is None:
        return pd.DataFrame()
    return pd.read_csv(file[0]["datapath"])

@render.data_frame
def summary():
    df = parsed_file()

    if df.empty:
        return pd.DataFrame()

    # Get the row count, column count, and column names of the DataFrame
    row_count = df.shape[0]
    column_count = df.shape[1]
    names = df.columns.tolist()
    column_names = ", ".join(str(name) for name in names)

    # Create a new DataFrame to display the information
    info_df = pd.DataFrame({
        "Row Count": [row_count],
        "Column Count": [column_count],
        "Column Names": [column_names],
    })

    # input.stats() is a list of strings; subset the columns based on the selected
    # checkboxes
    return info_df.loc[:, input.stats()]
import pandas as pd
from shiny import App, reactive, render, ui

app_ui = ui.page_fluid(
    ui.input_file(
        "input_file", "Choose CSV File", accept=[".csv"], multiple=False
    ),
    ui.input_checkbox_group(
        "stats",
        "Summary Stats",
        choices=["Row Count", "Column Count", "Column Names"],
        selected=["Row Count", "Column Count", "Column Names"],
    ),
    ui.output_data_frame("summary"),
)

def server(input, output, session):
    @reactive.calc
    def parsed_file():
        file = input.input_file()
        if file is None:
            return pd.DataFrame()
        return pd.read_csv(file[0]["datapath"])

    @render.data_frame
    def summary():
        df = parsed_file()

        if df.empty:
            return pd.DataFrame()

        # Get the row count, column count, and column names of the DataFrame
        row_count = df.shape[0]
        column_count = df.shape[1]
        names = df.columns.tolist()
        column_names = ", ".join(str(name) for name in names)

        # Create a new DataFrame to display the information
        info_df = pd.DataFrame({
            "Row Count": [row_count],
            "Column Count": [column_count],
            "Column Names": [column_names],
        })

        # input.stats() is a list of strings; subset the columns based on the selected
        # checkboxes
        return info_df.loc[:, input.stats()]

app = App(app_ui, server)
No matching items