I want to write dictionary contents to file and save. I just got this message: TypeError: argument should be a bytes-like object or ASCII string, not 'tuple'
#Creation of dictionary
final_dict = {}
final_dict['file_name']=d['filename']
final_dict1 = {}
final_dict1['binary']=temp
final_dict1['type']=temp1
V10=((['file_name']),(['binary']),(['type']))
print(V10)
(['file_name'], ['binary'], ['type'])
outputfile = open('XXXXX.pptx', 'wb')
outputfile.write(base64.b64decode(V10))
outputfile.close()
TypeError Traceback (most recent call last)
Input In [34], in <cell line: 2>()
1 outputfile = open('XXXXX.pptx', 'wb')
----> 2 outputfile.write(base64.b64decode(V1))
3 outputfile.close()
File ~\Anaconda3\lib\base64.py:80, in b64decode(s, altchars, validate)
65 def b64decode(s, altchars=None, validate=False):
66 """Decode the Base64 encoded bytes-like object or ASCII string s.
67
68 Optional altchars must be a bytes-like object or ASCII string of length 2
(...)
78 in the input result in a binascii.Error.
79 """
---> 80 s = _bytes_from_decode_data(s)
81 if altchars is not None:
82 altchars = _bytes_from_decode_data(altchars)
File ~\Anaconda3\lib\base64.py:45, in _bytes_from_decode_data(s)
43 return memoryview(s).tobytes()
44 except TypeError:
---> 45 raise TypeError("argument should be a bytes-like object or ASCII "
46 "string, not %r" % s.__class__.__name__) from None
TypeError: argument should be a bytes-like object or ASCII string, not 'tuple'
Note: What I expect to write to the variable:
{'file_name': 'ABCDERFROOEKWWKE.pptx'} {'binary': 'UEsXAAIXXXXXXXXXXXXXXXAACclAAATAAgCW0NvbnRlbnRfVHlwZXNdLFFFFBAIooAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA...
CodePudding user response:
To be written to a file, objects first need to be converted to str
or bytes
object depending on the writing mode
(see Methods of File Objects):
with open(file_name, "w") as file:
file.write(str( my_object ))
If you want to encode (not decode) it in base64 just call b64encode
on str(my_object).encode()
in binary mode
If instead, you want to decode the values of your dictionary before writing it, then just construct a new dictionary {k: b64decode(v) for k, v in old_dict.items()}
Also, since you used json as a tag, have a look at json.dump
(Saving structured data with json)