codenamea
V2EX  ›  Python

POST 上传的 excel(xls)文件,如何直接读进 pandas,避免写入到磁盘?

By codenamea at 2016 年 9 月 20 日 · 3791 次点击
csv 文件我可以这样写代码,已测试没有问题。但是 execl 文件用 TextIOWrapper 好像不行。

file = request.files['files']
csvfile = io.TextIOWrapper(file.stream, encoding='gbk')
reader = csv.reader(csvfile)

然而我 pandas 读取 excel 的时候:

file = request.files['files']
execlfile = io.TextIOWrapper(file.stream)
data_from_excel = pd.read_excel(execlfile, header=0, encoding='gbk')

报错:
builtins.UnicodeDecodeError
UnicodeDecodeError: 'gbk' codec can't decode byte 0xba in position 22: illegal multibyte sequence
编码这里我换了 gbk,utf-8 都不行


但是当我尝试着本地读取的话,简单一句就能成功读取了。。
temp=pd.read_excel("1.xls")
所以到底是哪里出了问题?
3 条回复  •  2016-09-27 11:24:29 +08:00
glasslion
   1
glasslion  
   2016 年 9 月 20 日
`execlfile = io.TextIOWrapper(file.stream) ` 这里需要指明 encoding 吧
codenamea
   2
codenamea  
OP
   2016 年 9 月 23 日
@glasslion 我后面说了编码这里我换了 gbk,utf-8 都不行
Arthur2e5
   3
Arthur2e5  
   2016 年 9 月 27 日
当你尝试用 TextIOWrapper 钦定这东西是有效的某种编码的纯文本的时候就已经在犯了用记事本打开文件的错误了。你要在已有的 stream (已经是 file-like 了吧?)上面再构造 file-like 的话可以看看 io.BufferedReader 之类的东西,反正不要搞 text 。
推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
© 2026 V2EX · 29ms · 3.9.8.5