在使用文件和加密库时,读取文件时遇到问题。详细信息如下,
出现以下异常:
Traceback (most recent call last):
File "F:/PyCharm Python Works/OpenCity/main_directory/main_file.py", line 8, in <module>
fe.encrypt_file(z2[0], z2[1])
File "F:\PyCharm Python Works\OpenCity\cryptograph\file_encryptor.py", line 4, in encrypt_file
keys = kr.read_keys()
File "F:\PyCharm Python Works\OpenCity\cryptograph\key_reader.py", line 3, in read_keys
f1 = open('keys.key', 'rb')
FileNotFoundError: [Errno 2] No such file or directory: 'keys.key'
密码器 file_decryptor.py:
def decrypt_file(x, y):
from cryptograph import key_reader as kr
from cryptography.fernet import Fernet
keys = kr.read_keys()
key = keys[0]
input_file = x
output_file = y
with open(input_file, 'rb') as f:
data = f.read()
f1 = Fernet(key)
encrypted = f1.decrypt(data)
with open(output_file, 'wb') as f:
f.write(encrypted)
file_encryptor.py:
def encrypt_file(x, y):
from cryptograph import key_reader as kr
from cryptography.fernet import Fernet
keys = kr.read_keys()
key = keys[0]
input_file = x
output_file = y
with open(input_file, 'rb') as f:
data = f.read()
f2 = Fernet(key)
encrypted = f2.encrypt(data)
with open(output_file, 'wb') as f:
f.write(encrypted)
key_reader.py:
def read_keys():
from typing import List
f1 = open('keys.key', 'rb')
f2: List[bytes] = []
data: bytes
for data in f1:
f2.append(data)
print(f2)
return f2
main_file.py:
from cryptograph import file_encryptor as fe
from cryptograph import file_decryptor as fd
z1r = open('files.txt', 'r')
z2 = []
for data in z1r:
data = data.rstrip('\n')
z2.append(data)
fe.encrypt_file(z2[0], z2[1])
fd.decrypt_file(z2[1], z2[2])
我刚刚完成了高级类别。 密码记录仪就是问题所在。一切正常,除了main_file引起问题。
答案 0 :(得分:0)
错误的确切原因是
"File "F:\PyCharm Python Works\OpenCity\cryptograph\key_reader.py", line 3, in
read_keys
f1 = open('keys.key', 'rb')"
这归咎于没有keys.key文件。 因此,您应该确认“ F:\ PyCharm Python Works \ OpenCity \ cryptograph \”目录中是否存在“ keys.key”文件。
答案 1 :(得分:0)
确保将keys.key
文件保存在key_reader.py
所在的位置。
或者改用绝对路径,例如:
f1 = open('F:/path/to/file/key.key', 'rb')
答案 2 :(得分:0)
使用os.chdir()
更改目录有助于解决此问题。
参考代码:
import cryptograph.key_writer
key_writer.write_key('keys.key', 1)
cryptograph / key_writer.py
import os
def write_key(file, number_of_keys):
# create key
keys = []
for i in range(number_of_keys):
key.append(create_key())
os.chdir('./cryptograph')
# write keys to file
with open(file, 'w') as f:
for key in keys:
f.write(key)
return None # it is fine not to have this return stmt, but I like to have it.