如何检查我上传的文件是 CSV 格式还是 Excel?在 python

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

 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())    

如果我上传 excel 文件会出错,我明白为什么。在以 csv 或 excel 格式读取之前,我必须检查上传文件的扩展名。如何查看上传文件的扩展名?

如果我理解正确的话,有一个简单的选项。

file_split = uploaded_file.split('.')
file_extension = '' if len(file_split) != 2 else file_split[1]
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")

我对BytesIO 的概念不是很清楚。我用这种方法尝试了很多 splitting.Its 作品,但这不是有效的方法。