加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 带二进制文件的StringIO?

发布时间:2020-12-16 21:55:45 所属栏目:Python 来源:网络整理
导读:我似乎得到了不同的输出: from StringIO import *file = open('1.bmp','r')print file.read(),'n'print StringIO(file.read()).getvalue() 为什么?是因为StringIO只支持文本字符串或其他东西吗? 最佳答案 当你调用file.read()时,它会将整个文件读入内存.

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读