Search code examples
pythonpython-3.xprotocol-buffers

Protobuf (Python): read binary data file and assign the data to repeated object


I have a protobuf file as below.

syntax = "proto3";

message Message {
   repeated bytes data = 1;
}

This is the Python code.

import test_pb2
message = test_pb2.Message()
with open("test.dat", mode='rb') as file:
   message.data.extend(file.read())

This is the error.

Traceback (most recent call last):
  File "./test.py", line 7, in <module>
    message.data.extend(file.read())
TypeError: 48 has type int, but expected one of: bytes

I also try "read_bytes()", similar error.

The following code works fine.

x = list()
with open("test.dat", mode='rb') as file:
   x.extend(file.read())

Seemingly, the repeated object does not work like list.


Solution

  • Try:

    import test_pb2
    
    message = test_pb2.Message()
    
    with open("test.dat",mode="rb") as file:
        message.data.extend([file.read()])
    
    print(message.data)
    

    file.read() returns bytes but you need Iterable[bytes]