Streamlit上传TXT文件遇两类TypeError错误,求解决方案
问题解决建议
错误原因分析
- TypeError: expected str, bytes or os.PathLike object, not UploadedFile:Streamlit的
st.file_uploader返回的是UploadedFile对象,不是本地文件路径,不能直接用open()或当作路径处理。 - TypeError: 'UploadedFile' object is not subscriptable:直接遍历
file.read()返回的字符串时,会按单个字符拆分,导致后续对单个字符做切片操作(如line[:11])出错。
修复后的完整代码
import streamlit as st import pandas as pd def read_txt_file(file, start_line): # 读取文件内容并按换行符分割为行列表,过滤空行 file_data = file.read().decode('utf-8') # 解码字节流为字符串 lines = [line.strip() for line in file_data.split('\n') if line.strip()] # 从指定行开始处理 target_lines = lines[start_line:] data = [] for line in target_lines: if line.startswith(('ECC Production', '-', ' ', 'Whithouse S', '----------','|Date')): continue row = {} row['Date'] = line[:11].replace('|', '').strip() row['Time'] = line[11:20].replace('|', '').strip() row['Supplier'] = line[20:31].replace('|', '').strip() row['Changed By'] = line[31:44].replace('|', '').strip() row['Field Name'] = line[44:75].replace('|', '').strip() row['CoCd'] = line[75:80].replace('|', '').strip() row['POrg'] = line[80:85].replace('|', '').strip() row['New Value'] = line[85:121].replace('|', '').strip() row['Old Value'] = line[121:156].replace('|', '').strip() data.append(row) df = pd.DataFrame(data) df = df.loc[~df['Date'].isin(['----------'])] df = df.loc[~df['Date'].isnull()] return df # 返回处理后的DataFrame,原代码缺失此步骤 input_files = st.file_uploader("INPUT Extraction", type=["txt"]) input2_files = st.file_uploader("INPUT2 Extraction", type=["txt"]) if st.button("Run"): if input_files and input2_files: input_df = read_txt_file(input_files, start_line=5) input2_df = read_txt_file(input2_files, start_line=18) final_df = pd.concat([input_df, input2_df], ignore_index=True) st.dataframe(final_df)
关键修改点
- 将
UploadedFile读取的字节流解码为字符串,再按换行符拆分为行列表,避免按单个字符遍历。 - 过滤空行,防止后续处理空字符串引发异常。
- 函数末尾添加
return df,确保调用时能获取到处理后的DataFrame(原代码缺失此步骤会导致concat操作失败)。
内容的提问来源于stack exchange,提问作者waterwalk93
相关产品推荐
相关产品推荐

