Skip to content Skip to sidebar Skip to footer

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' I wish for only '\x03'. Where is the extra character coming

Solution 1:

There is no extra character. You have a bytes object, whose contents are the single byte \x03.

The print function prints the str representation of any object. A bytes object prints out as 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).

To convince yourself of this fact, try print(len(my_bytes)) or print(my_bytes[0]). The length is 1; the first value is the (byte) number 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.)

Post a Comment for "In Python3, When I'm Reading A Binary File Why Does 'b' Become Prepended To My Content?"