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

2014-02-26 14:27:27 +08:00
 sedgwickz
描述可能不够准确,大致是这样的,我使用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
3648 次点击
所在节点    Python
8 条回复
likexian
2014-02-26 14:29:58 +08:00
fout = open("输出文件路径","wb")
img = x.photo.file.read()
fout.write(img)
sedgwickz
2014-02-26 14:31:20 +08:00
sedgwickz
2014-02-26 14:32:31 +08:00
@likexian 不好意思 是我的错 确实是你这么写的 但是我本地没有要输出的文件路径,如何在内存中建立一个对象呢?
est
2014-02-26 14:36:37 +08:00
fout.close()
lucifer9
2014-02-26 16:21:17 +08:00
tempfile.SpooledTemporaryFile ?
tonic
2014-02-26 17:01:02 +08:00
from cStringIO import StringIO?
lynx
2014-02-26 18:30:10 +08:00
python2: str, (c)StringIO.StringIO
python3: bytes, io.BytesIO

这些都可以
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 类型的字符串就会出错。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/101950

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX