在python中以二进制形式编写ASCII字符串 [英] Writing an ASCII string as binary in python

查看:217
本文介绍了在python中以二进制形式编写ASCII字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASCII字符串="abcdefghijk".我想使用python将其写入二进制格式的二进制文件.

I have a ASCII string = "abcdefghijk". I want to write this to a binary file in binary format using python.

我尝试了以下操作:

str  = "abcdefghijk"
fp = file("test.bin", "wb")
hexStr = "".join( (("\\x%s") % (x.encode("hex"))) for x in str)
fp.write(hexStr)
fp.close()

但是,当我打开test.bin时,我看到的是ascii格式而不是二进制格式的内容.

However, when I open the test.bin I see the following in ascii format instead of binary.

\x61\x62\x63\x64\x65\x66\x67

我理解这一点,因为这里有两个斜杠("\\ x%s").我该如何解决这个问题?提前致谢.

I understand it because for two slashes here ("\\x%s"). How could I resolve this issue? Thanks in advance.

更新:

以下给了我预期的结果:

Following gives me the expected result:

file = open("test.bin", "wb")
file.write("\x61\x62\x63\x64\x65\x66\x67")
file.close() 

但是如何使用"abcdef" ASCII字符串实现此目的. ?

But how do I achieve this with "abcdef" ASCII string. ?

推荐答案

您误解了\xhh在Python字符串中的作用.在Python字符串中使用\x表示法是正义语法来产生某些代码点.

You misunderstood what \xhh does in Python strings. Using \x notation in Python strings is just syntax to produce certain codepoints.

您可以使用'\x61'生成字符串,也可以使用'a';两种方式都只是说出给我一个带有十六进制值61的字符的字符串的方式,例如a ASCII字符:

You can use '\x61' to produce a string, or you can use 'a'; both are just two ways of saying give me a string with a character with hexadecimal value 61, e.g. the a ASCII character:

>>> '\x61'
'a'
>>> 'a'
'a'
>>> 'a' == '\x61'
True

那么\xhh语法不是;最终结果中没有\x61字符.

The \xhh syntax then, is not the value; there is no \ and no x and no 6 and 1 character in the final result.

您应该只写您的字符串:

somestring = 'abcd'

with open("test.bin", "wb") as file:
    file.write(somestring)

二进制文件没有什么不可思议的.与以文本模式打开的文件的唯一区别在于,二进制文件不会自动将\n换行符转换为平台的行分隔符标准;例如在Windows上,编写\n会生成\r\n.

There is nothing magical about binary files; the only difference with a file opened in text mode is that a binary file will not automatically translate \n newlines to the line separator standard for your platform; e.g. on Windows writing \n produces \r\n instead.

您当然不必产生十六进制转义符来写入二进制数据.

You certainly do not have to produce hexadecimal escapes to write binary data.

在Python 3上,字符串是Unicode数据,不能不经过编码就直接写入文件,但是在Python上,str类型是已经编码的字节.因此,在Python 3上,您将使用:

On Python 3 strings are Unicode data and cannot just be written to a file without encoding, but on Python the str type is already encoded bytes. So on Python 3 you'd use:

somestring = 'abcd'

with open("test.bin", "wb") as file:
    file.write(somestring.encode('ascii'))

或者您将使用字节字符串文字; b'abcd'.

or you'd use a byte string literal; b'abcd'.

这篇关于在python中以二进制形式编写ASCII字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆