Streamlit-txt文件上传和解析问题



我想通过streamlit导入程序上传一个Txt文件,并用我的"解析函数";(已测试并工作(。我有一个带有解析功能的app.py:

def parse(file, condition, data=[], ind_append=False):
for line in file:
...
return data

在app.py中,我也有上传文件的主函数,但无法成功应用解析函数。

def main():
file = st.file_uploader("Choose a file")
if file is not None:
st.write(file)
data = []
condition = '5'
ind_append = False
with open(file, encoding='utf8') as f:
data = parse(f, condition, data, ind_append)
df_2 = pd.DataFrame(data, columns=["1", "2", "3", "4", "5", "6", "7"])
st.markdown(download_csv(df_2), unsafe_allow_html=True)

Streamlight在线路中返回错误

with open(file, encoding='utf8') as f:

你知道怎么写得更好吗?如果我有一个单独的带有解析函数代码的parse.app和一个带有以下代码的单独笔记本,我就可以在Jupyter实验室成功地运行这个程序:

data = []
condition = '5'
ind_append = False
with open(file, encoding='utf8') as f:
data = parse(f, condition, data, ind_append)
df_2 = pd.DataFrame(data, columns=["1", "2", "3", "4", "5", "6", "7"])

我没有看到完整的错误,但查看了您的代码:

file = st.file_uploader("Choose a file")

已经是一个打开的文件,这意味着您可以像其他打开的文件一样开始迭代file。我想你有这个错误是因为你试图打开一个已经打开的文件。在这种情况下,应删除

with open(file, encoding='utf8') as f:

然后继续进行剩下的操作。

所以你的代码应该看起来像:

if file is not None:
st.write(file)
data = []
condition = '5'
ind_append = False
bytes_data = file.getvalue() # Modified
data = parse(bytes_data, condition, data, ind_append)

您可以使用python字符串/进行解析

在StringIO对象的close((方法被调用。

# with type you restict what file types you expect and you handle for each
file = st.file_uploader("Choose a file",type=["txt",'csv','xlsx'])
if file:
# this will write UploadedFile(id=2, name='test.txt', type='text/plain', size=666)
st.write(uploaded_file)
if file.type=='text/plain':
from io import StringIO
stringio=StringIO(file.getvalue().decode('utf-8'))
read_data=stringio.read()
st.write(read_data)

最新更新