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

Epic Wink
  • 796
  • 13
  • 18
  • Possible duplicate of [Python how to write to a binary file?](https://stackoverflow.com/questions/18367007/python-how-to-write-to-a-binary-file) – Chiheb Nexus Jun 02 '17 at 11:38

1 Answers1

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

Epic Wink
  • 796
  • 13
  • 18
  • 2
    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 – Jean-François Fabre Jun 02 '17 at 11:40