简体   繁体   English

如何在python中将二进制和asci数据写入文件?

[英]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 ? 我有这个有线协议我正在实现,我必须将二进制和ASCII数据写入同一个文件,我怎样才能同时执行此操作,或者至少结果将是具有混合asci和二进制数据的文件?

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! 我知道open("myfile", "rb")确实以二进制模式打开myfile,除了我找不到解决方法如何解决这个问题!

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 ). Python 2或3(*就在Python2中它是str ,我们在Python 3中将其更改为更清晰明确的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 ). 通常,如果要处理Unicode字符串,则使用编码( Python 3中的str ,Python 2中的unicode )。 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. open(filename, "wb")并没有真正做到你认为它做的事情 - 它只会影响新行的处理方式。

Under Python 2, the only difference binary mode makes is how newlines are translated when writing; 在Python 2下, 唯一不同的二进制模式是在写入时如何翻译换行符; \\n would be translated to the platform-dependant line separator. \\n将被转换为依赖于平台的行分隔符。

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. 换句话说,只需将ASCII字节字符串直接写入二进制文件,就Python而言,ASCII数据和二进制数据之间没有区别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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