简体   繁体   中英

How do I write binary data to a text file in Python?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM