我似乎得到了不同的输出:
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')
。file.read()
实际上返回了一个空字符串。你应该使用file.seek(0)
来倒回内部文件偏移量。你不应该使用"r"
来打开文件,而应该使用"rb"
,因为这种模式假定你只处理ASCII字符和EOF。
r
表示二进制模式。此外,请不要在您的帖子中添加标语/签名。 - agf