V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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
codenamea
V2EX  ›  Python

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

  •  
  •   codenamea · 2016-09-20 14:54:21 +08:00 · 2612 次点击
    这是一个创建于 2746 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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-09-20 22:40:04 +08:00
    `execlfile = io.TextIOWrapper(file.stream) ` 这里需要指明 encoding 吧
    codenamea
        2
    codenamea  
    OP
       2016-09-23 11:20:24 +08:00
    @glasslion 我后面说了编码这里我换了 gbk,utf-8 都不行
    Arthur2e5
        3
    Arthur2e5  
       2016-09-27 11:24:29 +08:00
    当你尝试用 TextIOWrapper 钦定这东西是有效的某种编码的纯文本的时候就已经在犯了用记事本打开文件的错误了。你要在已有的 stream (已经是 file-like 了吧?)上面再构造 file-like 的话可以看看 io.BufferedReader 之类的东西,反正不要搞 text 。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4306 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 10:13 · PVG 18:13 · LAX 03:13 · JFK 06:13
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.