【问题标题】:Writing a base64 string to file in python not working在python中将base64字符串写入文件不起作用
【发布时间】:2018-12-06 20:36:01
【问题描述】:

我从一个 POST 请求中得到一个 base64 编码的字符串。我想在解码后将它存储在我的文件系统中的特定位置。所以我写了这段代码,

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 格式时有什么需要注意的吗?

【问题讨论】:

    标签: file base64


    【解决方案1】:

    此行返回字节:

    file_content=base64.b64decode(file_content)
    

    在python3中运行这个脚本,它返回了这个exetion:

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

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

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

    【讨论】:

    • 成功了。谢谢。但是如果编码的字符串也包含图像,它也会起作用吗?
    • 图像是字节,所以当你保存它时它也必须是字节,我认为你不需要使用解码。但是您必须以字节写入模式打开文件。在打开的情况下(“数据/q1.jpg”,“wb”)
    猜你喜欢
    • 2016-10-27
    • 1970-01-01
    • 2011-01-30
    • 1970-01-01
    • 2018-11-18
    • 2012-01-02
    • 2014-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多