Writing a base64 string to file in python not working

本小妞迷上赌 提交于 2019-12-23 04:26:13

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/53651409/writing-a-base64-string-to-file-in-python-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!