简体   繁体   English

在Python3中,当我读取二进制文件时,为什么'b'会放在内容之前?

[英]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.

相关问题 为什么我的代码不起作用? 我是在 Python3 上使用 pandas 的新手 - Why does my code not work? I'm a novice at working with pandas on Python3 为什么我的 virtualenv python3 在我的本地机器上工作正常,但当我将 virtualenv 上传到服务器时却不行? - Why does my virtualenv python3 work fine on my local machine but not when I upload the virtualenv to the server? 我的 python output 缺少 1 个单词,我不确定为什么(从文件中读取) - My python output is missing 1 word and I'm not sure why(reading from file) 为什么线性搜索比Python3中的二进制搜索运行得更快? - Why does my linear search run faster than my binary search in Python3? 为什么 Python3 在读取 Python2 没有的文本文件时会出现 UnicodeDecodeError? - Why does Python3 get a UnicodeDecodeError reading a text file where Python2 does not? 读取二进制文件stdin时Python3中的UnicodeDecodeError - UnicodeDecodeError in Python3 when reading binary files stdin 从文本文件读取和打印时如何防止程序添加不需要的空行-Python3 - How can I prevent my program from adding unwanted blank lines when reading and printing from text file - Python3 当我尝试读取二进制文件时,Python在做什么? - What is Python doing when I'm trying to read a binary file? Python - 从二进制文件读取时如何删除“b”? - Python - How To Remove The 'b' When Reading From Binary Files? 为什么我的 Python 代码在读取文本文件时会打印额外的字符“”? - Why does my Python code print the extra characters "" when reading from a text file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM