Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert file to base64 string on Python 3

I need to convert image (or any file) to base64 string. I use different ways, but result is always byte, not string. Example:

import base64

file = open('test.png', 'rb')
file_content = file.read()

base64_one = base64.encodestring(file_content)
base64_two = base64.b64encode(file_content)

print(type(base64_one))
print(type(base64_two))

Returned

<class 'bytes'>
<class 'bytes'>

How do I get a string, not byte? Python 3.4.2.

like image 660
Vladimir37 Avatar asked Feb 27 '16 18:02

Vladimir37


2 Answers

Base64 is an ascii encoding so you can just decode with ascii

>>> import base64
>>> example = b'\x01'*10
>>> example
b'\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01'
>>> result = base64.b64encode(example).decode('ascii')
>>> print(repr(result))
'AQEBAQEBAQEBAQ=='
like image 198
tdelaney Avatar answered Oct 17 '22 17:10

tdelaney


I need to write base64 text in file ...

So then stop worrying about strings and just do that instead.

with open('output.b64', 'wb'):
  write(base64_one)
like image 28
Ignacio Vazquez-Abrams Avatar answered Oct 17 '22 17:10

Ignacio Vazquez-Abrams