5

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?

1
  • 2
    with that code, the second file.read() would get nothing. You should use seek(0) before reading the file again. Sep 26, 2011 at 16:32

3 Answers 3

8

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

2
  • Yes, you're right. That didn't completely solve my real world problem, then I figured out I was writing the data in 'w' mode and getting corrupt files, not 'wb'. Now everything works :)
    – Joelmc
    Sep 26, 2011 at 17:48
  • I think that file.seek(0), proposed by minhee, is a much better approach.
    – Gallaecio
    Jun 3, 2016 at 15:16
5

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

-1

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?

1
  • On some platforms (and everywhere on Python 3) just r means binary mode. Also, please also don't add taglines / signatures to your posts.
    – agf
    Sep 28, 2011 at 17:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.