繁体   English   中英

如何修复 python 中的文件列表中没有属性“名称”错误

[英]how to fix no atribute 'name' error in a list of files in python

我正在使用带有 python 的 streamlit,以便允许用户上传多个文件,而不是将内容显示为 dataframe。

但首先我需要检查它的csv类型还是xls ,并显示类型和名称。

问题是在检查文件类型时它会崩溃并显示以下错误:

AttributeError: 'list' object has no attribute 'name'
Traceback:
File "F:\AIenv\lib\site-packages\streamlit\script_runner.py", line 333, in _run_script
    exec(code, module.__dict__)
File "f:\AIenv\streamlit\app2.py", line 766, in <module>
    main()
File "f:\AIenv\streamlit\app2.py", line 300, in main
    file_details = {"filename":data.name,

请注意,如果我上传单个文件,则脚本运行时没有错误。

代码:

import streamlit as st
import pandas as pd

def main():

   if st.sidebar.checkbox("Multiple Files"):
          data = st.sidebar.file_uploader('Multiple Excel files', type=["csv","xlsx","xls"], 
          accept_multiple_files=True)
          for file in data:
              file.seek(0)
    
   elif st.sidebar.checkbox("Single File"):    
          data = st.sidebar.file_uploader("Upload Dataset",type=["csv","xlsx","xls"])
        
   if data is not None:        
          # display the name and the type of the file
          file_details = {"filename":data.name,
                           "filetype":data.type
                        }
          st.write(file_details)

if __name__=='__main__':
    main()

在这种情况下, data应该是一个list类型(您可以使用type(data)检查)。

你可以做的是改变:

   if data is not None:        
          # display the name and the type of the file
          file_details = {"filename":data.name,
                           "filetype":data.type
                        }
          st.write(file_details)

至:

if data is not None and len(data) > 0:
  st.write("filename {} | filetype: {}".format(data[i].name, data[i].type) for i in range(len(data)))

如果选中“多个文件”,您正在尝试访问文件列表的名称和类型。 我建议统一您的“数据”结构并使其始终成为一个列表。 然后你必须迭代它:

import streamlit as st
import pandas as pd

def main():
    if st.sidebar.checkbox("Multiple Files"):
        data = st.sidebar.file_uploader('Multiple Excel files', type=["csv","xlsx","xls"], 
            accept_multiple_files=True)
        for file in data:
            file.seek(0)
    
    elif st.sidebar.checkbox("Single File"):    
        data = st.sidebar.file_uploader("Upload Dataset",type=["csv","xlsx","xls"])
        if data is not None:
            data = [data]
        
    if data is not None:
        for file in data:
            # display the name and the type of the file
            file_details = {"filename":file.name,
                            "filetype":file.type
            }
            st.write(file_details)

if __name__=='__main__':
    main()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM