3

I want to use the function base64.encode() to directly encode the contents of a file in Python.

The documentation states:

base64.encode(input, output)

Encode the contents of the binary input file and write the resulting base64 encoded data to the output file. input and output must be file objects.

So I do this:

encode(open('existing_file.dat','r'), open('output.dat','w'))

and get the following error:

>>> import base64
>>> base64.encode(open('existing_file.dat','r'), open('output.dat','w'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/base64.py", line 502, in encode
    line = binascii.b2a_base64(s)
TypeError: a bytes-like object is required, not 'str'

To my eye that looks like a bug in /usr/lib/python3.6/base64.py but a big part of me does not want to believe that...

1
  • 1
    try to open file in byte mode: rb/wb Commented Jun 19, 2017 at 11:19

1 Answer 1

8

from docs

when opening a binary file, you should append 'b' to the mode value to open the file in binary mode

so changing

encode(open('existing_file.dat','r'), open('output.dat','w'))

to

encode(open('existing_file.dat','rb'), open('output.dat','wb'))

should work

Sign up to request clarification or add additional context in comments.

Comments

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.