Divyanshu Gupta
Divyanshu Gupta

Reputation: 103

How to read file, convert binary buffer to binary string and later convert the binary string to binary buffer again in python?

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

Upvotes: 0

Views: 153

Answers (1)

RufusVS
RufusVS

Reputation: 4127

As much as I avoid eval, try this:

file_content_bytes = eval(file_content_str)

Upvotes: 1

Related Questions