Home > front end >  How can I check the file I am uploading is in CSV format or Excel? in python
How can I check the file I am uploading is in CSV format or Excel? in python

Time:09-21

 uploaded_file = st.file_uploader("Choose a file")
    if uploaded_file is not None:
        data = pd.read_csv(uploaded_file)
        #Get overview of data
        st.write(data.head())  
    else:
        data = pd.read_excel(uploaded_file)
        #Get overview of data
        st.write(data.head())    

It gives me error if I upload excel file, and I understand why. I have to check the uploaded file's extension before reading it in csv or excel format. HOW to check the uploaded file's extension?

CodePudding user response:

If I understood You correctly, there is a simple option.

file_split = uploaded_file.split('.')
file_extension = '' if len(file_split) != 2 else file_split[1]

CodePudding user response:

uploaded_file = st.file_uploader("Choose a file")
    #converting dic to str 
    conv1 = str(uploaded_file)

#Read file type csv and excel only
    #splitting 
    split1 = conv1.split(sep=':', maxsplit=1)
    store1 = split1[0]
    store2 = store1.split(sep="'", maxsplit=-1)
    store2 = store2[1].split(sep='.', maxsplit=1)
    if store2[1]=="csv":
        st.write("ok")
        df = pd.read_csv(uploaded_file)
        st.write(df.head())
    elif store2[1]=="xlsx": 
        st.write("NotOk")
        df = pd.read_excel(uploaded_file)
        st.write(df.head())
    else:
        st.write("Error: upload the file in csv or excel format")

My concepts on ByteIO is not clear. I tried this way with lots of splitting.Its works but this is not efficient way though.

  • Related