0

I need to write text, then binary data to a file. For example, I would like to write the file with contents:

BESTFORMAT
NUMLINES 42
FIELDS FOO BAR SPAM
DATATYPES INT32 FLOAT64 FLOAT64
FILETYPE BINARY
???d?'Ӈ T???'Ѥ??X??\??
?? R??&??X??\???????
??zR??X??\????????
...

However, in Python you can't open a file in a way that you can write ASCII data, then binary data.


I've tried:

  • Converting my binary data to text (no good, as it outputs b'5 42.7 0.8'

  • Encoding my text data to binary and opening the file as binary (no good, as then I have a binary file). Edit: it turns out this was working, but I needed to open the file in my text editor with UTF-8 encoding

1

1 Answer 1

0

Multiple solutions:

  1. Write text data, then re-open in append binary mode and write binary data
with open("file", "w") as f:
    f.write("text")
with open("file", "ab") as f:
    f.write(b"bytes")
  1. Convert the text data to bytes
with open("file", "wb") as f:
    f.write("text".encode())
    f.write(b"bytes")
  1. Write the text data to a text wrapper
import io
with open("file", "wb") as f:
    f_text = io.TextIOWrapper(f, write_through=True)
    f_text.write("text")
    f.write(b"bytes")

Note: some text editors will see non-utf-8 bytes in the file and view the file in hexadecimal mode. To see the text, re-open the file in the text editor in UTF-8 encoding

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

1 Comment

you could have used fl.write(b"BESTFORMAT\n\ NUMLINES 42\n\ FIELDS FOO BAR SPAM\n\ DATATYPES INT32 FLOAT64 FLOAT64\n\ FILETYPE BINARY\n\ ") so you could have used the binary mode of the file

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.