用Python加密和解密文件

用Python加密和解密文件,python,file,encryption,Python,File,Encryption,我正在做一个项目,我需要加密文件,将它们复制到另一个文件夹,并能够用另一个.py解密它们 问题是,我看到很多例子,但没有一个是有效的。。。很明显,我想我做错了什么,所以我在这里寻求指导 我用于生成密钥的代码(此代码有效): 这就是问题所在。这是我加密文件的代码,但它给出了错误FileNotFoundError:[Errno 2]没有这样的文件或目录:“DocumentoEncriptado.txt.encrypted” from cryptography.fernet import Fernet

我正在做一个项目,我需要加密文件,将它们复制到另一个文件夹,并能够用另一个.py解密它们

问题是,我看到很多例子,但没有一个是有效的。。。很明显,我想我做错了什么,所以我在这里寻求指导

我用于生成密钥的代码(此代码有效):

这就是问题所在。这是我加密文件的代码,但它给出了错误
FileNotFoundError:[Errno 2]没有这样的文件或目录:“DocumentoEncriptado.txt.encrypted”

from cryptography.fernet import Fernet

file = open('key.key', 'rb')
key = file.read()
file.close

with open('DocumentoEncriptado.txt', 'rb') as f:
    data = f.read()

fernet = Fernet(key)
encrypted = fernet.encrypt(data)

with open('DocumentoEncriptado.txt.encrypted', 'rb') as f:
    f.write(encrypted)
行中:

with open('DocumentoEncriptado.txt.encrypted', 'rb') as f:
您正在尝试读取文件“DocumentoEncriptado.txt.encrypted”,因为文件模式为 设置为“rb”。 似乎没有这个名字的文件。 您只需要将文件模式更改为“wb”。 所以就变成这样

 with open('DocumentoEncriptado.txt.encrypted', 'wb') as f:

打开DocumentoEncriptado.txt.encrypted文档,使用“write”标志,而不是“read”标志:打开('DocumentoEncriptado.txt.encrypted',wb')天哪,就是这样,我没有看到打字错误!非常感谢。
 with open('DocumentoEncriptado.txt.encrypted', 'wb') as f: