Loading csv file from github repo in streamlit application

I have an application that works perfectly localy but doesnt when it is connected to streamlit share. The reason is that the code has to access and load a csv file to function, locally this is simply saved in the same working directory, but for the streamlit share i have saved it in the same private github repository as the python script. Then in the script i would use the github URL to access the csv file

def load_original_data():
# Load CSV file from GitHub raw URL
url = ‘https://github.com/[username]/[repository]/blob/main/[file].csv
response = requests.get(url)
if response.status_code == 200:
return pd.read_csv(StringIO(response.text))
else:
st.error(“Failed to load data from GitHub.”)
return No

however it returns failed to load when opening up the application, any help please?

Welcome to the community, @henrycity3! We’re excited to see you join and engage on our forum! :hugs:

The issue you’re facing when trying to load a CSV file from GitHub in your Streamlit app might be due to the URL you’re using.

It seems like you’re trying to use the regular GitHub URL, which doesn’t directly serve the raw content of the file. You should use the raw content URL provided by GitHub for such purposes.

Best,
Charly

Here’s how you can correctly access and load a CSV file from a GitHub repo in your app:

  1. Get the raw URL: Navigate to your CSV file on GitHub, click “Raw” to access the direct raw URL which starts with https://raw.githubusercontent.com/.

  2. Update your function:

    import pandas as pd
    import requests
    from io import StringIO
    import streamlit as st
    
    def load_original_data():
        url = 'https://raw.githubusercontent.com/[username]/[repository]/main/[file].csv'
        response = requests.get(url)
        if response.status_code == 200:
            return pd.read_csv(StringIO(response.text))
        else:
            st.error("Failed to load data from GitHub.")
            return None
    

Let me know if that works for you :slight_smile:

Best,
Charly