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...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With