python – 带二进制文件的StringIO?

我似乎得到了不同的输出:

from StringIO import *

file = open('1.bmp','r')

print file.read(),'\n'
print StringIO(file.read()).getvalue()

为什么?是因为StringIO只支持文本字符串或其他东西吗?

最佳答案
当你调用file.read()时,它会将整个文件读入内存.然后,如果再次在同一个文件对象上调用file.read(),它将已经到达文件的末尾,因此它只返回一个空字符串.

相反,尝试例如重新打开文件:

from StringIO import *

file = open('1.bmp','r')
print file.read(),'\n'
file.close()

file2 = open('1.bmp','r')
print StringIO(file2.read()).getvalue()
file2.close()

您还可以使用with语句使代码更清晰:

from StringIO import *

with open('1.bmp','r') as file:
    print file.read(),'\n'

with open('1.bmp','r') as file2:
    print StringIO(file2.read()).getvalue()

顺便说一句,我建议以二进制模式打开二进制文件:open(‘1.bmp’,’rb’)

相关文章

Python中的函数(二) 在上一篇文章中提到了Python中函数的定...
Python中的字符串 可能大多数人在学习C语言的时候,最先接触...
Python 面向对象编程(一) 虽然Python是解释性语言,但是它...
Python面向对象编程(二) 在前面一篇文章中谈到了类的基本定...
Python中的函数(一) 接触过C语言的朋友对函数这个词肯定非...
在windows下如何快速搭建web.py开发框架 用Python进行web开发...