Ashish Pani
Ashish Pani

Reputation: 1071

Writing a base64 string to file in python not working

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?

Upvotes: 8

Views: 34964

Answers (2)

rrossmiller
rrossmiller

Reputation: 56

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

Upvotes: 2

Lucas Resende
Lucas Resende

Reputation: 612

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

Upvotes: 21

Related Questions