[英]In Python3, when I'm reading a binary file why does 'b' become prepended to my content?
For example I'm trying to read a file as follows 例如,我正在尝试如下读取文件
fd = open('mydb.dbf', 'rb')
print(fd.read(1))
The output is: 输出为:
b'\\x03'
b'\\ x03'
I wish for only '\\x03'. 我只希望输入'\\ x03'。 Where is the extra character coming from?
多余的字符从哪里来?
There is no extra character. 没有多余的字符。 You have a
bytes
object, whose contents are the single byte \\x03
. 您有一个
bytes
对象,其内容为单字节\\x03
。
The print
function prints the str
representation of any object. print
功能可打印任何对象的str
表示形式。 A bytes
object prints out as b'\\x03'
. bytes
对象打印为b'\\x03'
。 But that b
is no more part of the value than the quotes are (or, for that matter, the backslash, x, or two digits). 但是
b
的值不超过引号的值(或者,反斜杠,x或两位数)。
To convince yourself of this fact, try print(len(my_bytes))
or print(my_bytes[0])
. 为了使自己相信这一事实,请尝试使用
print(len(my_bytes))
或print(my_bytes[0])
。 The length is 1
; 长度为
1
; the first value is the (byte) number 3
. 第一个值是(字节)数字
3
。
(If you didn't want a bytes
object, you shouldn't have opened the file in binary mode. But, considering that the first character is a control-C, you probably did want a bytes
object.) (如果不需要
bytes
对象,则不应以二进制模式打开文件。但是,考虑到第一个字符是Control-C,则可能确实需要bytes
对象。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.