import base64
#code to load base64 data from file
encoded='ZGF0YSB0byBiZSBlbmNvZGVk'
outputdata=base64.decode(encoded)
Well I obviously had different code to handle the loading of the data from the file, but I have just changed the code to use a string with encoded data for this example.
If you try and run this code, you will get the following error:
Traceback (most recent call last):
File "removed", line 4, in <module>
outputdata=base64.decode(encoded)
TypeError: decode() takes exactly 2 arguments (1 given)
This was confusing as I couldn't find any more information about what should be in the second argument, so I tried a few different things, nothing works. If you do this, the error will instead change to the following:
Traceback (most recent call last):
File "removed", line 4, in <module>
outputdata=base64.decode(encoded, '')
File "C:\Python27\lib\base64.py", line 303, in decode
line = input.readline()
AttributeError: 'str' object has no attribute 'readline'
The problem was that I was infact calling the wrong function name. There are 2 separate functions, and the function I thought I was using, takes just a string, and the function that I was actually using takes 2 parameters, and I think is intended to read from a file on this disk.
So this is quite an easy fix, which is to instead use the function base64.b64decode(encoded_data), and just means I wasn't reading the manual well enough. I am documenting it here because Googling the previous error messages along with some keywords about base64 and decoding didn't turn up anything. It was only when I went back to the very basic example that I noticed my error. Thus the final working code is as follows:
import base64
#code to load base64 data from file
encoded='ZGF0YSB0byBiZSBlbmNvZGVk'
outputdata=base64.b64decode(encoded)
print(outputdata)
No comments:
Post a Comment