0

I opened a file (.jpeg) in binary format and stored it's content in a variable and converted the binary buffer into string using str(). Now, I want to convert the string into binary buffer again.

from tkinter import filedialog
file_path = filedialog.askopenfilename()
file = open(file_path,"rb")
file_content = file.read()
file.close()
print(file_content)
file_content_str = str(file_content)
print(file_content)

# want a code to convert file_content_str into bytes again here
# file_content_bytes = file_content_string converted to bytes

# file2 = open("moon2.jpg", "w+b")
# file2.write(file_content_bytes)
# file2.close()

1 Answers1

1

As much as I avoid eval, try this:

file_content_bytes = eval(file_content_str)

RufusVS
  • 4,008
  • 3
  • 29
  • 40
  • I tried this but there is difference in file_content_str and file_content_bytes file_content_str = b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00`\x00`\x00\x00\xff.......... file_content_bytes = b'b\'\\xff\\xd8\\xff\\xe0\\x00\\x10JFIF\\x00\\x01\\x01\\x01\\x00`\\x00`\\x00\\x00\\xff........ – Divyanshu Gupta Jun 14 '20 at 04:58