I have a number of Python bytes objects stored in a text file, that Python prints like "b'\x80\x03}q\x00.'" How do I convert each of these back into a bytes object?
In other words, I'm trying to find a function that does convert("b'\x80\x03}q\x00.'") == b'\x80\x03}q\x00.'.
I feel like this should be trivial, but none of these obvious approaches worked:
>>> s = "b'\x80\x03}q\x00.'"
>>> bytes(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string argument without an encoding
>>> bytes(s.encode())
b"b'\xc2\x80\x03}q\x00.'"
>>> bytes(s[2:-1].encode())
b'\xc2\x80\x03}q\x00.'
>>> bytes(s[2:-1].encode('utf8'))
b'\xc2\x80\x03}q\x00.'
>>> eval(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: source code string cannot contain null bytes
>>> exec(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: source code string cannot contain null bytes
bytesliterals, notbytesobjects. How did this file get created in the first place?bytesliteral. Withs = "...",\x00, for example, is replace with an actual null byte, rather than remaining the 4 characters that represent a null byte in a literal. If you writes = r"...", thenast.literal_eval(s)returns thebytesobject you want.sin this example; ifsis read from a file, like e.g.s = f.readline(), this isn't an issue.bytes(s[2:-1].encode())[1:] # b'\x80\x03}q\x00.'