StringIO 与二进制文件?
我似乎得到了不同的输出:
from StringIO import *
file = open('1.bmp', 'r')
print file.read(), '\n'
print StringIO(file.read()).getvalue()
为什么?是不是因为StringIO只支持文本字符串什么的?
I seem to get different outputs:
from StringIO import *
file = open('1.bmp', 'r')
print file.read(), '\n'
print StringIO(file.read()).getvalue()
Why? Is it because StringIO only supports text strings or something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您调用
file.read()
时,它会将整个文件读入内存。然后,如果您在同一个文件对象上再次调用 file.read() ,它已经到达文件末尾,因此它只会返回一个空字符串。相反,请尝试重新打开文件:
您还可以使用
with
语句使代码更清晰:顺便说一句,我建议以二进制模式打开二进制文件:
open('1. bmp', 'rb')
When you call
file.read()
, it will read the entire file into memory. Then, if you callfile.read()
again on the same file object, it will already have reached the end of the file, so it will only return an empty string.Instead, try e.g. reopening the file:
You can also use the
with
statement to make that code cleaner:As an aside, I would recommend opening binary files in binary mode:
open('1.bmp', 'rb')
第二个
file.read()
实际上只返回一个空字符串。您应该执行file.seek(0)
来倒回内部文件偏移量。The second
file.read()
actually returns just an empty string. You should dofile.seek(0)
to rewind the internal file offset.难道您不应该使用
"rb"
打开,而不仅仅是"r"
,因为此模式假定您仅处理 ASCII 字符和 EOF?Shouldn't you be using
"rb"
to open, instead of just"r"
, since this mode assumes that you'll be processing only ASCII characters and EOFs?