【发布时间】:2021-06-07 09:44:57
【问题描述】:
我正在使用cryptography.fernet 加密文本文件,然后使用write 函数将其写入我的文件中,但我收到错误write() argument must be a str not a byte。代码如下:
from cryptography.fernet import Fernet
message = open("D:/raaghav/code/os/user/password.txt", mode='w')
messageR = open("D:/raaghav/code/os/user/password.txt", mode='r')
messageRe= messageR.read()
key = Fernet.generate_key()
fernet = Fernet(key)
encMessage = fernet.encrypt(messageRe.encode())
message.write(encMessage)
print("original string: ", message)
print('encrypted message: ', encMessage)
【问题讨论】:
-
str(encMessage)可能会有所帮助。只需将其替换为您写入文件的位置 -
以
"wb"模式打开文件进行写入。另外:使用with在写入之前关闭您正在读取的文件。基本上:1.打开 2.读取 3.关闭 4.打开 5.写入 6.关闭 -
@Sujay 这真的行不通。
str(b'hello')不会给你字符串"hello"它会给你"b'hello'",包括b和嵌入的引号。通过decode成员函数转换为字符串。 -
在您还指定编码之前,字节不会直接对应于文本。在纯 7 位 ASCII 文本的情况下,这种映射是微不足道的;但是对于其他任何事情,您确实需要知道文本编码。
-
@tripleee:但是对于加密和解密,我们甚至可以将文本文件作为二进制数据读取,不是吗?加密也适用于二进制文件。无需知道编码。
标签: python python-cryptography