json TypeError:参数应该是类似字节的对象或ASCII字串,而不是'tuple'

zy1mlcev  于 2022-11-19  发布在  其他
关注(0)|答案(1)|浏览(358)

我要将字典内容写入档案并保存。我刚收到这个消息:TypeError:参数应该是类似字节的对象或ASCII字串,而不是'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'

注意:我希望写入变量的内容:
{'文件名':'二进制':"我的天啊,我的天啊,我的天啊!"

ddrv8njm

ddrv8njm1#

要将对象写入文件,首先需要根据写入模式将对象转换为strbytes对象(请参阅文件对象的方法):

with open(file_name, "w") as file:
    file.write(str( my_object ))

如果你想用base64编码(而不是解码)它,只需在str(my_object).encode()上以二进制模式调用b64encode
相反,如果您希望在编写字典之前对它的值进行解码,那么只需构造一个新的字典{k: b64decode(v) for k, v in old_dict.items()}
此外,由于您使用了json作为标记,请查看json.dump(使用json保存结构化数据)

相关问题