I'm just starting to learn how to work with python binary files, and i'm trying to write information into a file in binary mode. Since apparently there's no newline command for bytes (like \n for strings), what is the easiest way to keep different chunks (of different sizes) of information separated in a binary file? Ideally i would like to have different lines for it, but i cannot find a way to do so.
1 Answer
What you are referring to is an encoding - the way the bits/bytes in a binary file should be interpreted.
All files are binary files as they are stored. It is only when they are displayed/transmitted/processed that the encoding becomes important.
For example, the bytes 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x21, 0x0A, 0x65, 0x41, 0x42, 0x43 might be displayed as
Hello!
ABC
If there were interpreted as part of a text file by a text editor, because the bytes are ASCII text and 0x0A is a newline character.
However, the same sequence of bytes would be interpreted very differently if they were part of a JPEG file (for example).
As an example of a binary encoding, in a JPEG file each logical piece of image information is called a segment. Each segment starts with a marker. Each marker starts with the byte 0xFF. This is the 'separator' between logical pieces of information.
\nis used to represent line breaks. You'll have to do something similar.C structand then write (or read) the structs (records) from/to a file. See thestructPython module.pickleformat for ideas.