【问题标题】:StringIO with binary files?带有二进制文件的 StringIO?
【发布时间】:2011-11-25 08:51:05
【问题描述】:

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

from StringIO import *

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

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

为什么?是不是因为StringIO只支持文本字符串什么的?

【问题讨论】:

  • 使用该代码,第二个 file.read() 将一无所获。您应该在再次读取文件之前使用 seek(0)。

标签: python string file stringio


【解决方案1】:

当您调用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”。现在一切正常:)
  • 我认为 minhee 提出的 file.seek(0) 是一个更好的方法。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    您不应该使用"rb" 打开而不是仅使用"r",因为此模式假定您将只处理 ASCII 字符和 EOF?

    【讨论】:

    • 在某些平台上(以及 Python 3 上的任何地方),r 表示二进制模式。另外,请不要在您的帖子中添加标语/签名。
    猜你喜欢
    • 2012-03-03
    • 1970-01-01
    • 2011-07-11
    • 2012-03-25
    • 1970-01-01
    • 2015-01-12
    • 2014-11-29
    • 2016-06-15
    相关资源
    最近更新 更多