开发者

StringIO with binary files?

开发者 https://www.devze.com 2023-04-07 23:20 出处:网络
I seem to get different outputs: from StringIO import * file = open(\'1.bmp\', \'r\') print file.read(), \'\\n\'

I seem to get different outputs:

from StringIO import *

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

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

Why? Is it because StringIO only supports text strings or 开发者_运维知识库something?


When you call file.read(), it will read the entire file into memory. Then, if you call file.read() again on the same file object, it will already have reached the end of the file, so it will only return an empty string.

Instead, try e.g. reopening the file:

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

You can also use the with statement to make that code cleaner:

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

As an aside, I would recommend opening binary files in binary mode: open('1.bmp', 'rb')


The second file.read() actually returns just an empty string. You should do file.seek(0) to rewind the internal file offset.


Shouldn't you be using "rb" to open, instead of just "r", since this mode assumes that you'll be processing only ASCII characters and EOFs?

0

精彩评论

暂无评论...
验证码 换一张
取 消