23

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.

1
  • @AlastairMcCormack I need to write base64 text in file, then to read it later. Commented Feb 27, 2016 at 18:44

3 Answers 3

35

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=='
Sign up to request clarification or add additional context in comments.

Comments

2

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)

1 Comment

I great solution but only if you are not also writing other strings to the file.
0

The following code worked for me:

import base64

file_text = open(file, 'rb')
file_read = file_text.read()
file_encode = base64.encodebytes(file_read)

I initially tried base64.encodestring() but that function has been deprecated as per this issue.

1 Comment

Watch out -- base64.encodebytes will insert \n characters "after every 76 bytes of output" per the docs.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.