blv210
blv210

Reputation: 23

ReConvert bytes to a file Python

For a personal project i would like to convert files of any types (pdf, png, mp3...) to bytes type and then reconvert the bytes file to the original type. I made the first part, but i need help for the second part.

In the following example, I read a .jpg file as bytes and i save its content in the "content" object. Now i would like to reconvert "content" (bytes type) to the original .jpg type.

test_file = open("cadenas.jpg", "rb")
content = test_file.read()
content

b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x0 ...

Could you help me ?

Regards

Upvotes: 0

Views: 162

Answers (1)

yannvm
yannvm

Reputation: 428

Pictures uses Base64 encoding. This should do the job.

import base64

test_file = open('cadenas.jpg', 'rb')
content = test_file.read()

content_encode = base64.encodestring(content)
content_decode = base64.decodebytes(content_encode) 

result_file = open('cadenas2.jpg', 'wb')
result_file.write(content_decode)

Upvotes: 1

Related Questions