二进制文件中如何使用StringIO?

5

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

from StringIO import *

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

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

为什么?是因为StringIO只支持文本字符串或类似的东西吗?

2
使用那段代码后,第二个 file.read() 将得不到任何内容。在再次读取文件之前,您应该使用 seek(0)。 - Facundo Casco
3个回答

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()

你也可以使用 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')

是的,你说得对。那并没有完全解决我的实际问题,后来我发现我在'w'模式下写入数据并得到了损坏的文件,而不是'wb'。现在一切都正常了 :) - Joelmc
我认为minhee提出的file.seek(0)是一个更好的方法。 - Gallaecio

5
第二个file.read()实际上返回了一个空字符串。你应该使用file.seek(0)来倒回内部文件偏移量。

-1

你不应该使用"r"来打开文件,而应该使用"rb",因为这种模式假定你只处理ASCII字符和EOF。


在某些平台上(以及 Python 3 上的任何地方),只有 r 表示二进制模式。此外,请不要在您的帖子中添加标语/签名。 - agf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接