在Python中将base64字符串写入文件无法正常工作 [英] Writing a base64 string to file in python not working

查看:582
本文介绍了在Python中将base64字符串写入文件无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从POST请求中获取了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))

这正在/data/创建文件,但是该文件为空.它不包含解码的字符串.没有权限问题. 但是当我不是file_content时,向文件写入"Hello World".这是工作.为什么python无法将base64解码的字符串写入文件?它也不会引发任何异常.处理base64格式时,我需要注意些什么吗?

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?

推荐答案

此行返回字节:

file_content=base64.b64decode(file_content)

在python3中运行此脚本,它返回以下指令:

Running this script in python3, it returned this exetion:

write()参数必须为str,而不是字节

write() argument must be str, not bytes

您应该将字节转换为字符串:

You should convert bytes to string:

b"ola mundo".decode("utf-8") 

尝试

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

这篇关于在Python中将base64字符串写入文件无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆