【问题标题】:How can I check the file I am uploading is in CSV format or Excel? in python如何检查我上传的文件是 CSV 格式还是 Excel 格式?在蟒蛇
【发布时间】:2021-11-14 01:32:45
【问题描述】:
 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 格式阅读之前,我必须检查上传文件的扩展名。如何查看上传文件的扩展名?

【问题讨论】:

标签: python excel pandas csv streamlit


【解决方案1】:

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

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

【讨论】:

  • 提示:uploaded_fileBytesIO 对象(子类),而不是 str。您可以通过uploaded_file.name 访问文件名。建议:我会将您的代码修改为ext = uploaded_file.name.split(".")[-1] if "." in uploaded_file.name else None
  • 如果您能将 BytesIO 上的任何链接转发给我,那就太好了。 @蒂姆斯
【解决方案2】:
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")

我对 ByteIO 的概念不清楚。我尝试了这种方式进行了很多拆分。它的工作原理,但这不是有效的方式。

【讨论】:

  • 您是否尝试过使用uploaded_file.name?恕我直言 ext = uploaded_file.name.split(".")[-1] 应该给你扩展名。
  • 它给出了以下错误AttributeError: 'dict' object has no attribute 'name'
  • 好的,你可以试试ext = uploaded_file["name"].split(".")[-1]
猜你喜欢
  • 2011-10-03
  • 1970-01-01
  • 2013-10-25
  • 1970-01-01
  • 2014-06-24
  • 1970-01-01
  • 1970-01-01
  • 2016-12-11
  • 2012-10-01
相关资源
最近更新 更多