Reputation: 8958
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...
Upvotes: 3
Views: 11314
Reputation: 10953
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
Upvotes: 8