Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a base64 string to file in python not working

Tags:

file

base64

I am getting a base64 encoded string from a POST request. I wanted to store it in my filesystem at a particular location after decoding . So i have written this code,

try:
   file_content=base64.b64decode(file_content)
   with open("/data/q1.txt","w") as f:
        f.write(file_content)
except Exception as e:
   print(str(e))

This is creating the file at /data/ but the file is empty. It is not containing the decoded string. There is no permission issue. But when i am instead of file_content writing 'Hello World' to the file. It is working. Why python is not able to write base64 decoded string to the file? It is not throwing any exception also. Is there something i need to take care when dealing with base64 format?

like image 238
Ashish Pani Avatar asked Dec 06 '18 12:12

Ashish Pani


1 Answers

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))
like image 108
Lucas Resende Avatar answered Oct 25 '22 18:10

Lucas Resende