Gradio Blocks调用自定义CSV/Excel读取函数报错的解决咨询
解决Gradio中File组件触发的AttributeError问题
问题场景
本地测试读取CSV/Excel文件的函数可正常输出数据,但将该函数绑定到Gradio Blocks的gr.File组件change事件时,触发AttributeError: '_io.BufferedRandom' object has no attribute 'endswith'错误。
错误原因
本地测试时,read_file函数接收的是字符串类型的文件路径,可以直接用endswith判断后缀;但Gradio的gr.File组件默认传入的是文件对象(_io.BufferedRandom类型),该对象没有endswith方法,因此报错。
解决方案
提供两种可行方案,按需选择:
方案1:修改函数处理文件对象
直接基于Gradio传入的文件对象操作,通过file_obj.name获取文件名判断后缀,同时将文件对象直接传入pandas读取函数:
import gradio as gr import pandas as pd def read_file(file_obj): file_name = file_obj.name if file_name.endswith('.csv'): data = pd.read_csv(file_obj) elif file_name.endswith('.xlsx') or file_name.endswith('.xls'): data = pd.read_excel(file_obj) else: raise ValueError('不支持的文件类型,请上传CSV或Excel文件。') return data with gr.Blocks() as demo: file_input = gr.File() # 添加Dataframe组件用于在UI展示数据 output_table = gr.Dataframe() file_input.change(fn=read_file, inputs=file_input, outputs=output_table) demo.launch(debug=True)
方案2:让Gradio返回文件路径字符串
通过设置gr.File的type="filepath"参数,让组件直接返回文件路径字符串,这样原有的read_file函数无需修改:
import gradio as gr import pandas as pd def read_file(file_path): if file_path.endswith('.csv'): data = pd.read_csv(file_path) elif file_path.endswith('.xlsx') or file_path.endswith('.xls'): data = pd.read_excel(file_path) else: raise ValueError('不支持的文件类型,请上传CSV或Excel文件。') return data with gr.Blocks() as demo: # 设置type="filepath"返回文件路径字符串 file_input = gr.File(file_count="single", type="filepath") output_table = gr.Dataframe() file_input.change(fn=read_file, inputs=file_input, outputs=output_table) demo.launch(debug=True)
补充说明
两种方案都添加了gr.Dataframe组件,用于在UI界面展示读取后的表格数据,解决原代码中outputs=[]无法展示数据的问题。
内容的提问来源于stack exchange,提问作者ah bon
相关产品推荐
相关产品推荐

