我似乎得到了不同的输出:
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 - 带有二进制文件的 StringIO?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7558168/