Search code examples
pythonbinarybuffering

What is a suitable buffer for Python's struct module


In Python I'm accessing a binary file by reading it into a string and then using struct.unpack(...). Now I want to write to that string using struct.pack_into(...), but I get the error "Cannot use string as modifiable buffer". What would be a suitable buffer for use with the struct module?


Solution

  • If you aren't trying to pack it into a specific object, just use struct.pack to return a string.

    Otherwise, ctypes.create_string_buffer is one way to obtain a mutable buffer.