如何修复 Python msgpack TypeError: write() argument must be str, not bytes

问题:

尝试使用 msgpack 将对象写入文件时,使用类似这样的代码

write_msgpack_text_mode.py
with open("myobj.msgpack", "w") as outfile:
    msgpack.dump(myobj, outfile)

你看到类似这样的错误消息

msgpack_traceback.txt
File /usr/lib/python3/dist-packages/msgpack/__init__.py:26, in pack(o, stream, **kwargs)
    20 """
    21 Pack object `o` and write it to `stream`
    22
    23 See :class:`Packer` for options.
    24 """
    25 packer = Packer(**kwargs)
---> 26 stream.write(packer.pack(o))

TypeError: write() argument must be str, not bytes

解决方案

msgpack 写入二进制数据,因此你需要使用 open(..., "wb") 以二进制模式打开文件:

write_msgpack_binary.py
with open("myobj.msgpack", "wb") as outfile:
    msgpack.dump(myobj, outfile)

Check out similar posts by category: Python