Home > front end >  Bytes not the same when converting from bytes to string to bytes
Bytes not the same when converting from bytes to string to bytes

Time:04-16

I have the following problem. When I read the bytes of an file via with open(r'file-path', 'rb') as file: data = file.read() and write this byte object "data" into in other file using 'wb'. The out coming file is fine and there are no problems. But when I first convert the byte object "data" into a string data_str = str(data) and than convert it back using new_data = data_str.encode() "new_data" looks exactly the same as "data", but if I write "new_data" into a file the file isn´t working. Or as in my case not recognized as being an mp3 file, even though the bytes are the same on the first look.

I know it seems useless to convert the bytes into a string and than back into bytes, but in my case I really have to do that.

CodePudding user response:

data_str.encode() expects data_str to be the result of data.decode().

str(data) doesn't return a decoded byte string, it returns the printed representation of the byte string, what you would type as a literal in a program. If you want to convert that back to a byte string, use ast.literal_eval().

import ast

with open(r'file-path', 'rb') as file: 
    data = file.read()
    str_data = str(data)
    new_data = ast.literal_eval(str_data)
    print(new_data == data)
  • Related