python - 带有二进制文件的 StringIO?

标签 python string file stringio

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

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/

相关文章:

c# - 测试空字符串不会抛出 NullReferenceException

string - 此 x86 汇编代码如何创建字符串?

php - 使用php上传后如何重命名文件名?

python - 将元素添加到列表时运行代码

python - 使用 python 数据表按组排列的前 N ​​行

c - 在C中查找字符数组的保留内存大小

iphone - Xcode 4 中是否有用于组织的 "best practice"?

java - 在目录中创建文件之前检查目录中的写访问权限

python - 将数据拆分为单列

python - 如何删除未命名的 header ?