[英]Streamlit - txt file upload and parse problem
我想通過 streamlit 導入器上傳一個 txt 文件,並用我的“解析函數”(經過測試並且有效)解析它。 我有一個解析 function 的 app.py:
def parse(file, condition, data=[], ind_append=False):
for line in file:
...
return data
在 app.py 我也有主要的 function 我上傳我的文件,但無法成功應用我的解析 function 到它。
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)
Streamlit 在行中返回錯誤
with open(file, encoding='utf8') as f:
知道如何更好地寫這個嗎? 如果我有一個單獨的 parse.app 和我的 parse function 代碼和帶有以下代碼的單獨 nootbook,我可以在 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:
並繼續操作您的 rest。
所以你的代碼應該是這樣的:
if file is not None:
st.write(file)
data = []
condition = '5'
ind_append = False
file = file.decode('UTF-8')
data = parse(file, condition, data, ind_append)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.