When opening an uploaded csv file :TypeError: expected str, bytes or os.PathLike object, not UploadedFile

Hi all,

I am still fairly new to Streamlit but I have created an analysis program and am running locally. I was originally running through the terminal with no issues and proceeded to create my Streamlit page to run the analysis through it. The issue arises when I try to open an uploaded file which was uploaded via the st.file_uploader. The file is a .csv or .xls and the file is then passed into another python file and opened. However, when I try to open the file I get this error:

“TypeError: expected str, bytes or os.PathLike object, not UploadedFile”

Here is the rough code:
uploaded_file = st.file_uploader(“Upload Raw Data for analysis”, type=[“.csv”, “.xls”])

Then in the other file:
with open(uploaded_file, “r”") as f:

I error right after this line.

I have tried to encode it (looking at the encoding it is ANSI), opening as “rb” and nothing seems to clear the error. I have tried other options listed in the documents page such as:

bytes_data = uploaded_file.getvalue()
stringio = StringIO(uploaded_file.getvalue().decode(“utf-8”)) or “ANSI”

I have been able to do this before using .txt files but obviously I understand if a different method is needed for csv. I am hoping it’s something simple I’m just missing. Any thoughts would be greatly appreciated!
:slight_smile:

Pam

UPDATE: I should add that I’d like to read the file line by line to grab specific information. It was working this way before I made the streamlit page but now that I am pulling the file in via st.file_uploader() I am getting these issues.

What would you like to do with your CSV file? A typical pattern is:

import streamlit as st
import pandas as pd

file =st.file_uploader("test", type="csv")
if file:
    df = pd.read_csv(file)
    df

Thanks mathcatsand. I should have added that I want to be able to read the csv line by line to grab specific information but the data is not in a traditional table format and there are specific values that need to be extracted line by line. I was able to do this without the streamlit page no problem but now that it is uploaded via streamlit it does not work.

import streamlit as st
import io

file =st.file_uploader("test", type="csv")
if file:
    wrapper = io.TextIOWrapper(file, encoding="utf-8")
    with wrapper as f:
        for line in f:
            st.markdown(line)

The object returned from the file uploader is already BytesIO so you don’t need to open it. If you iterate through it, you’ll get byte strings, so use a wrapper to declare the encoding.

1 Like

This worked, thank you! :slight_smile:

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.