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?
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With