[英]What does this error message mean and how to fix it?
我想使用 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
您正在解码(字节)字符串'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'))
并不是说您可以正确解码写入文件的值。 看起来您试图通过对其调用str()
将base64.b64encode()
的bytes
返回值转换为str
,但这会创建一个带有b'...'
的值。 您想从bytes
解码为str
,其中 Base64 字节始终可以解码为 ASCII。
但是,如果您要以二进制模式打开文件,则无需编码或解码即可正确写入和读取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)
我还将文件对象用作上下文管理器(通过with
语句),以便为您自动关闭它们。 请注意在文件模式中添加了b
( wb
用于写入二进制文件, rb
用于读取二进制文件)。
最后但并非最不重要的一点是,编码为 Base64 会增加文件的长度; 你几乎不能称之为压缩; 我会在这里选择不同的变量名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.