此错误消息的含义是什么以及如何解决?

时间:2016-04-04 10:38:10

标签: python python-3.x base64

我想使用base64对字符串进行编码,然后将其写入文本文件。然后我想打开文本文件并解码其内容(即找到原始字符串)。我继续收到此错误消息,我不确定它的含义以及如何修复我的代码以使其正常工作。

到目前为止,这是我的代码:

text = b"kpahw95R"
compressed = base64.b64encode(text)
print(compressed)
encoded = open("textfile.txt", "w")
encoded.write(str(compressed))
encoded.close()

decoded = open("textfile.txt", "r").read()
decompressed = base64.b64decode(b"decoded")
decoded.close()
print(decompressed)

错误讯息:

  File ".../python3.5/base64.py", line 90, in b64decode
    return binascii.a2b_base64(s)
binascii.Error: Incorrect padding

1 个答案:

答案 0 :(得分:1)

您正在解码(字节)字符串'decoded'。这不是有效的base64数据,并且错误告诉你它不是有效的base64长度,尽管它还有其他问题;如果您添加了正确的填充,则无法获得原始数据:

>>> import base64
>>> base64.b64decode(b'decoded')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mjpieters/Development/venvs/stackoverflow-3.5/lib/python3.5/base64.py", line 90, in b64decode
    return binascii.a2b_base64(s)
binascii.Error: Incorrect padding
>>> base64.b64decode(b'decoded=')
b'u\xe7(u\xe7'

您希望传入变量 decoded的值,但您需要首先将该数据编码为ASCII,以便函数接受它:

decompressed = base64.b64decode(decoded.encode('ascii'))

不是说您可以正确解码写入文件的值。您似乎尝试通过调用bytesbase64.b64encode()的{​​{1}}返回值转换为str,但这会在其周围创建一个str()的值。您希望解码b'...'改为bytes,其中Base64字节始终可以解码为ASCII。

但是,如果您要以二进制模式打开文件,则可以正确地编写和读取str,而无需编码或解码:

bytes

我还使用文件对象作为上下文管理器(通过text = b"kpahw95R" compressed = base64.b64encode(text) print(compressed) with open("textfile.txt", "wb") as encoded: encoded.write(compressed) with open("textfile.txt", "rb") as decoded: decompressed = base64.b64decode(decoded.read()) print(decompressed) 语句),以便它们自动关闭。请注意在文件模式中添加withb用于编写二进制文件,wb用于读取二进制文件。

最后但并非最不重要的是,对Base64的编码将增加文件的长度;你很难称之为压缩;我在这里选择不同的变量名称。