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()

6
  • 1
    For the way you converted it to string, "ast.literal_eval" should convert it back. Commented Jun 14, 2020 at 2:23
  • @MichaelButscher yes it worked, thanks Commented Jun 14, 2020 at 5:09
  • Out of curiosity where is "ast.literal_eval"? Commented Jun 14, 2020 at 5:21
  • @RufusVS This is short for: module "ast", function "literal_eval". Unlike "eval" it is safe to be used on unknown (potentially malicious) data. Commented Jun 14, 2020 at 5:26
  • @MichaelButscher Thanks! I will look up the ast module! Commented Jun 14, 2020 at 5:39

1 Answer 1

1

As much as I avoid eval, try this:

file_content_bytes = eval(file_content_str)

Sign up to request clarification or add additional context in comments.

1 Comment

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........

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.