Jefferson Alves Jefferson Alves - 1 month ago 26
Python Question

Python file.read() png bug?

I'm trying read a PNG image in pure text, as in the notepad. (For later turn in base64)

test images: http://imgur.com/a/sMX9t

So I tryed this code:

f = 'test1.png'
with open(f) as file:
for i in xrange(0, 5):
print(i, f, file.read())
print
f = 'test2.png'
with open(f) as file:
for i in xrange(0, 5):
print(i, f, file.read())


But it not read the entire file, such as "read" function is suppose to do.
If I try call "read" again for some PNGs, it read one more part, for others no, no matter how often call.

I only have this output:

(0, 'test1.png', '\x89PNG\n')
(1, 'test1.png', '')
(2, 'test1.png', '')
(3, 'test1.png', '')
(4, 'test1.png', '')

(0, 'test2.png', '\x89PNG\n')
(1, 'test2.png', '\xd2y\xb4j|\x8f\x0b5MW\x98D\x97\xfc\x13\\7\x11\xcaPn\x18\x80,}\xc6g\x90\xc5n\x8cDi\x81\xf9\xbel\xd6Fl\x11\xae\xdf s\xf0')
(2, 'test2.png', '')
(3, 'test2.png', '')
(4, 'test2.png', '')


But I wanna this:
http://i.stack.imgur.com/qvuvj.png

It's a bug?

Any other (simple) way to get this file in base64?

Sorry google translate...

Answer

PNG files are not text files; you must read them as binary files, not text files, like so:

with open(f, 'rb') as file:

If you want to produce the base64 encoding of the data, use the base64 module:

import base64
f = 'test1.png'
with open(f) as file:
    for i in xrange(0, 5):
        print(i, f, base64.b64encode(file.read()))