Python中将base64字符串写入文件不起作用

7

我从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/创建文件,但文件为空。它不包含解码后的字符串。没有权限问题。 但当我写入“Hello World”到文件而不是file_content时,它可以工作。为什么Python不能将base64解码后的字符串写入文件?它也没有抛出任何异常。在处理base64格式时,是否有需要注意的事项?

2个回答

20

这一行会返回字节:

file_content=base64.b64decode(file_content)
在Python3中运行此脚本后,出现以下异常:

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

它有效了。谢谢。但是如果编码的字符串中还包含图像,它也能工作吗? - Ashish Pani
2
图像是字节,因此保存时也必须是字节。我认为您不需要使用解码。但是,您将需要以字节写入模式打开文件。在打开案例中(“data / q1.jpg”,“wb”) - Lucas Resende

2
如前面的回答所说,f.write()函数需要字节作为参数。然而,你不需要将其转换为字符串,可以直接写入字节。
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))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接