Replace lines in a protobuf file using python
Question: I have an existing proto file that I would like to change. What I would like
to do is read the file in, change a value or two, and then write it back out
to disk as a .proto file, to be read by another program. According to [this
documentation](https://developers.google.com/protocol-
buffers/docs/reference/python/index), I should be able to write something like
this:

    
    
    from google.protobuf import message
    
    msg = message.Message()
    msg.ParseFromString(infile.read())
    
    ... (make changes)
    
    outfile.write(msg.SerializeToString())
    

But it just gives me a `NotImplementedError`. Where is the library I need to
interface with protobuf text files?
[This](https://developers.google.com/protocol-
buffers/docs/reference/cpp/google.protobuf.text_format) seems to work for C++,
why hasn't it been implemented for python? (No, the functions in
google.protobuf.text_format aren't implemented either).


Answer: You seem to be confusing several different concepts here.

`message.Message` is an abstract base class. You need to construct an instance
of the specific derived class you're interested in.

`.proto` files contain type definitions, not message data. You must compile
your `.proto` file using `protoc`, the Protocol Compiler. It will generate
Python code which you can then import into your program in order to construct
the specific type you want. Please see the [Protobuf
tutorial](https://developers.google.com/protocol-buffers/docs/pythontutorial)
for details.

Use `ParseFromString()` to parse _binary_ protobuf data from a file, and use
`SerializeToString()` to convert the message back into _binary_ data. You
should almost always use binary format for protobuf data.

The `TextFormat` class you reference implements an alternative encoding of
protobufs that is human-readable. This format is _not_ recommended for most
use cases. If you want a human-readable format, you may be better off with
JSON, but it will always be much slower and less-compact than binary
encodings. `TextFormat` is occasionally useful for debugging (printing out a
message) and sometimes for writing message data as source code. `TextFormat`
is available in the Python library as the [`text_format`
module](https://developers.google.com/protocol-
buffers/docs/reference/python/google.protobuf.text_format-module).

