StringIO与二进制文件?

Joe*_*lmc 5 python string file stringio

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

from StringIO import *

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

print file.read(), '\n'
print StringIO(file.read()).getvalue()
Run Code Online (Sandbox Code Playgroud)

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

Liq*_*ire 8

当你打电话时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()
Run Code Online (Sandbox Code Playgroud)

您还可以使用该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()
Run Code Online (Sandbox Code Playgroud)

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


min*_*hee 5

第二个file.read()实际上只返回一个空字符串.您应该file.seek(0)倒回内部文件偏移量.