How to fix Python msgpack TypeError: write() argument must be str, not bytes

Problem:

While trying to write an object to a file using msgpack using code like

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

you see an error message like

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

Solution

msgpack writes binary data, so you need to open the file in binary mode using open(..., "wb"):

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