Streamlit - txt file upload and parse problem

Viewed 81

I would like to upload a txt file via streamlit importer and parse it with my "parse function" (tested and works). I have an app.py with parse function:

def parse(file, condition, data=[], ind_append=False):
    for line in file:
    ...
return data

In app.py I also have main function where I upload my file, but cannot apply my parse function to it successfully.

def main():
    file = st.file_uploader("Choose a file")

    if file is not None:
        st.write(file)
        data = []
        condition = '5'
        ind_append = False
        with open(file, encoding='utf8') as f:
            data = parse(f, condition, data, ind_append)

        df_2 = pd.DataFrame(data, columns=["1", "2", "3", "4", "5", "6", "7"])
        st.markdown(download_csv(df_2), unsafe_allow_html=True)

Streamlit returns error in line

with open(file, encoding='utf8') as f:

Any idea how to write this better? I am successful in running this in Jupyter lab if I have a separate parse.app with my parse function code and separate nootbook with below code:

        data = []
        condition = '5'
        ind_append = False
        with open(file, encoding='utf8') as f:
            data = parse(f, condition, data, ind_append)

        df_2 = pd.DataFrame(data, columns=["1", "2", "3", "4", "5", "6", "7"])
1 Answers

I didn't see the complete error but looking at your code:

file = st.file_uploader("Choose a file")

is already an opened file, which means you can start iterating through file just like any other opened file. I think you have that error because you are trying to open a file which is already been opened. In this case you should remove:

with open(file, encoding='utf8') as f:

and proceed with the rest of your operation.

So your code should look like:

if file is not None:
    st.write(file)
    data = []
    condition = '5'
    ind_append = False

    bytes_data = file.getvalue() # Modified
    data = parse(bytes_data, condition, data, ind_append)
Related