Base64 is an ascii encoding so you can just decode with ascii
>>> import base64
>>> example = b'\x01'*10
>>> example
b'\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01'
>>> result = base64.b64encode(example).decode('ascii')
>>> print(repr(result))
'AQEBAQEBAQEBAQ=='
Answer from tdelaney on Stack OverflowBase64 is an ascii encoding so you can just decode with ascii
>>> import base64
>>> example = b'\x01'*10
>>> example
b'\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01'
>>> result = base64.b64encode(example).decode('ascii')
>>> print(repr(result))
'AQEBAQEBAQEBAQ=='
I need to write base64 text in file ...
So then stop worrying about strings and just do that instead.
with open('output.b64', 'wb'):
write(base64_one)
python - Encoding an image file with base64 - Stack Overflow
Python: Converting file to base64 encoding - Stack Overflow
Writing a base64 string to file in python not working - Stack Overflow
Converting Base64 file back to Excel
I'm not sure I understand your question. I assume you are doing something along the lines of:
import base64
with open("yourfile.ext", "rb") as image_file:
encoded_string = base64.b64encode(image_file.read())
You have to open the file first of course, and read its contents - you cannot simply pass the path to the encode function.
Edit: Ok, here is an update after you have edited your original question.
First of all, remember to use raw strings (prefix the string with 'r') when using path delimiters on Windows, to prevent accidentally hitting an escape character. Second, PIL's Image.open either accepts a filename, or a file-like (that is, the object has to provide read, seek and tell methods).
That being said, you can use cStringIO to create such an object from a memory buffer:
import cStringIO
import PIL.Image
# assume data contains your decoded image
file_like = cStringIO.StringIO(data)
img = PIL.Image.open(file_like)
img.show()
import base64
from PIL import Image
from io import BytesIO
with open("image.jpg", "rb") as image_file:
data = base64.b64encode(image_file.read())
im = Image.open(BytesIO(base64.b64decode(data)))
im.save('image1.png', 'PNG')
This line returns byte:
file_content=base64.b64decode(file_content)
Running this script in python3, it returned this exetion:
write() argument must be str, not bytes
You should convert bytes to string:
b"ola mundo".decode("utf-8")
try it
import base64
file_content = 'b2xhIG11bmRv'
try:
file_content=base64.b64decode(file_content)
with open("data/q1.txt","w+") as f:
f.write(file_content.decode("utf-8"))
except Exception as e:
print(str(e))
As a previous answer said, f.write() expects bytes. You don't need to convert to a string, however. You can write the bytes directly
import base64
file_content = 'b2xhIG11bmRv'
try:
file_content = base64.b64decode(file_content)
with open("data/q1.txt","wb") as f:
f.write(file_content)
except Exception as e:
print(str(e))