0

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.

5
  • You have to make your own encoding. Commented Nov 21, 2018 at 15:36
  • When a text file is encoded, there aren't empty gaps between the lines of text. Instead, a special character \n is used to represent line breaks. You'll have to do something similar. Commented Nov 21, 2018 at 15:39
  • you mean like defining a custom set of characters to mark a division in my information? Commented Nov 21, 2018 at 15:43
  • You may be interested in grouping your record data in a kind of C struct and then write (or read) the structs (records) from/to a file. See the struct Python module. Commented Nov 21, 2018 at 16:03
  • With structs of different sizes mixed, you need to know the type before a read or write. See also the pickle format for ideas. Commented Nov 21, 2018 at 16:07

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.