Live updating Dash based on a .csv file

Hello!

I have been trying to figure out how to live update Dash based on the content inside of a .csv file, but I just can’t get it to work.

So, I have the following code:

from dash import Dash, html, dcc
from jupyter_dash import JupyterDash
import pandas as pd
import time

df = pd.read_csv('C:\\Users\carri\Desktop\Tourney Sim Dash\players.csv')

def generate_table(dataframe, max_rows=100):
    return html.Table([
        html.Thead(
            html.Tr([html.Th(col) for col in dataframe.columns])
        ),
        html.Tbody([
            html.Tr([
                html.Td(dataframe.iloc[i][col]) for col in dataframe.columns
            ]) for i in range(min(len(dataframe), max_rows))
        ])
    ])

app = JupyterDash(__name__)

def layout():
    return html.Div([ html.H1('Tourney Sim'), generate_table(df) ])
app.layout = layout

if __name__ == '__main__':
    app.run_server(mode = "jupyterlab")

And it runs almost as expected, the dataframe is generated, all players from the “players.csv” file are printed along their values just fine, and the program runs.
I have a different program that constatly updates the .csv file while it runs, and it works just fine, now what I need to do is to make Dash refresh the dataframe to show the updates on the .csv file, which I am guessing I have to callbacks. I have been researching callbacks for well over two days now, and I just can’t, I don’t understand them. If anyone here could give me a helping hand and explaing to me how I should do it, I would appreciate it a lot. Thanks in advance!

Hello @markyy,

Welcome to the community!

First, have you looked into dash_table? It is really easily to make a table:

Second, yes, updating it will take using a callback. But, you’ll have to make some changes to your code.

Callbacks use ids, so you must provide them in your layout, else they won’t work. Plus, having ids is just good practice for elements on a page that you will reference.

Once you have an id setup, especially for the datatable. Assuming your column layout isn’t changing, you could setup an update to the data of the table with n_intervals.

Got it! I’m really new to this, so it might take me some time, but I will reach back to you with an update either when I get it to work following what you have told me, or when I get stuck again. Thank you!

1 Like

I managed to get it to work! TYSM

1 Like