简体   繁体   中英

How to write binary and asci data into a file in python?

I have this wired protocol I am implementing and I have to write binary and ASCII data into the same file, how can I do this at the same time or at least the result in the end will be the file with mixed asci and binary data ?

I know that open("myfile", "rb") does open myfile in the binary mode, except that I can't find a solution how to go about this!

What you write to a file is in fact "bytes". Python 2 or 3 (*Just that in Python2 it was str and we changed this to be more clear and explicit in Python 3 to bytes ).

So:

with open("file.ext", "w") as f:
    f.write(b"some bytes")

Example:

bash-4.3$ python
Python 2.7.6 (default, Apr 28 2014, 00:50:45) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> with open("file.ext", "w") as f:
...     f.write(b"some bytes")
... 
>>> 
bash-4.3$ cat file.ext
some bytesbash-4.3$ 

Normally you would use an encoding if you are dealing with Unicode strings ( str in Python 3, unicode in Python 2 ). eg:

s = "Hello World!"

with open("file.ext", "w") as f:
    f.write(s.encode("utf-8"))

Note: As mentioned in the comments; open(filename, "wb") doesn't really do what you think it does - it just affects how newlines are treated.

Under Python 2, the only difference binary mode makes is how newlines are translated when writing; \\n would be translated to the platform-dependant line separator.

In other words, just write your ASCII byte strings directly to your binary file, there is no difference between your ASCII data and the binary data as far as Python is concerned.

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