import save
string = ""
with open("image.jpg", "rb") as f:
byte = f.read(1)
while byte != b"":
byte = f.read(1)
print ((byte))
I'm getting bytes like:
b'\x00'
How do I get rid of this b''
?
Let's say I wanna save the bytes to a list, and then save this list as the same image again. How do I proceed?
Thanks!
You can use bytes.decode function if you really need to "get rid of b": http://docs.python.org/3.3/library/stdtypes.html#bytes.decode
But it seems from your code that you do not really need to do this, you really need to work with bytes.
To operate on binary data you can use the array-module. Below you will find an iterator that operates on 4096 chunks of data instead of reading everything into memory at ounce.
This is one way to get rid of the
b''
:If you want to save the bytes later it's more efficient to read the entire file in one go rather than building a list, like this:
The
b''
, is only the string representation of the data that is written when youprint
it.Using
decode
will not help you here because you only want the bytes, not the characters they represent. Slicing the string representation will help even less because then you are still left with a string of several useless characters ('\', 'x', and so on), not the original bytes.There is no need to modify the string representation of the data, because the data is still there. Just use it instead of the string (i.e. don't use
print
). If you want to copy the data, you can simply do:If you want to output the binary data directly from your program, use the
sys.stdout.buffer
:Here is one solution
print(str(byte[2:-1]))
The b"..." is just a python notation of byte strings, it's not really there, it only gets printed. Does it cause some real problems to you?