如何修复 Python 中文件列表中的无 atribute "name" 错误



我将streamlit与python一起使用,以便允许用户上传多个文件,而不是将内容显示为数据帧。

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

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

AttributeError: 'list' object has no attribute 'name'
Traceback:
File "F:AIenvlibsite-packagesstreamlitscript_runner.py", line 333, in _run_script
exec(code, module.__dict__)
File "f:AIenvstreamlitapp2.py", line 766, in <module>
main()
File "f:AIenvstreamlitapp2.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()

如果"多个文件";检查。我建议统一你的"数据"结构,并使其始终成为一个列表。然后你必须对它进行迭代:

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

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

相关内容

  • 没有找到相关文章

最新更新