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
sedgwickz
V2EX  ›  Python

用 Python 如何在内存中建立一个二进制数组对象?

  •  
  •   sedgwickz · 2014-02-26 14:27:27 +08:00 · 3632 次点击
    这是一个创建于 3716 天前的主题,其中的信息可能已经有所发展或是发生改变。
    描述可能不够准确,大致是这样的,我使用web.py框架,使用上传组件在后台可以得到这个文件的unicode流对象。
    img = x.photo.file.read()

    我如何根据这个x.photo.file得到它的二进制呢?

    网上之前有人是这样做的。
    fout = open("输出文件路径","rb")
    img = x.photo.file.read()
    fout.write(img)

    但我这里并没有输出文件,他只是临时在内存中存在,当以byte[]形式提交给服务器后就自动释放了。
    求指点,谢谢。

    我在stackoverflow也发问了,还木有人回复。
    http://stackoverflow.com/questions/22032639/how-to-get-file-binary-format-in-behind-code-of-web-py-framework
    第 1 条附言  ·  2014-02-27 09:11:13 +08:00
    感谢各位的回复。查询了一些资料后已经解决了。

    附上我的Gist链接。希望能帮助到有类似需求的朋友。

    8 条回复    1970-01-01 08:00:00 +08:00
    likexian
        1
    likexian  
       2014-02-26 14:29:58 +08:00   ❤️ 1
    fout = open("输出文件路径","wb")
    img = x.photo.file.read()
    fout.write(img)
    sedgwickz
        2
    sedgwickz  
    OP
       2014-02-26 14:31:20 +08:00
    sedgwickz
        3
    sedgwickz  
    OP
       2014-02-26 14:32:31 +08:00
    @likexian 不好意思 是我的错 确实是你这么写的 但是我本地没有要输出的文件路径,如何在内存中建立一个对象呢?
    est
        4
    est  
       2014-02-26 14:36:37 +08:00
    fout.close()
    lucifer9
        5
    lucifer9  
       2014-02-26 16:21:17 +08:00
    tempfile.SpooledTemporaryFile ?
    tonic
        6
    tonic  
       2014-02-26 17:01:02 +08:00
    from cStringIO import StringIO?
    lynx
        7
    lynx  
       2014-02-26 18:30:10 +08:00
    python2: str, (c)StringIO.StringIO
    python3: bytes, io.BytesIO

    这些都可以
    muzuiget
        8
    muzuiget  
       2014-02-26 20:25:47 +08:00
    你没说清楚你的 Python 版本,假设你是 Python 2,Python 2 的字符串有两种类型

    1. str 类型,这是默认的,就是 a = '中文',得到 '\xe4\xb8\xad\xe6\x96\x87'
    2. unicode 类型,a = u'中文',得到 u'\u4e2d\u6587'

    你所谓的「二进制数组」对象就是 str 类型的字符串。所以你的代码 img = x.photo.file.read(),img 不是你认为的「unicode流对象」,本来就是你想要的。

    fout.write 接受的参数就是需要一个 str 类型的字符串,如果是 unicode 类型的字符串就会出错。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2379 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 03:10 · PVG 11:10 · LAX 20:10 · JFK 23:10
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.