我正在开发一个保存加密密码的 tkinter 项目。我正在写这条路径的关键:
C:\Users\<usrname>\.PassManager\PassManager.key
。
工作正常,突然我不知道发生了什么,我收到了这个错误。在写作时,我提到要将 bytes 写入文件。好像没用啊
理解:
错误:
'bool' object
self.key_path()
不是布尔变量?
这个问题的原因是什么?
错误:
<class 'bytes'>
b'Oy21Nnu_A0f7xFuS-7pnFegt5Dj0ks6n4_ksOPzlYck=' #<-------Writing this key
Traceback (most recent call last):
File "c:\Users\rohit\Desktop\Password Manager\app.py", line 559, in <module>
app = App()
^^^^^
File "c:\Users\rohit\Desktop\Password Manager\app.py", line 40, in __init__
self.b64key = self.key()
^^^^^^^^^^
File "c:\Users\rohit\Desktop\Password Manager\app.py", line 522, in key
with open(self.key_path, "wb") as file:
TypeError: 'bool' object does not support the context manager protocol
代码:
class App(CTk):
def __init__(self):
super().__init__()
self.count = True
self.db_path = self.get_db_path()
self.key_path = self.get_key_path()
# Writing up db and key files
self.dirFile_setup()
# Secret key
self.b64key = self.key()
# --------------- Code -------------------------
def key():
if path.exists(self.key_path) and stat(self.key_path).st_size == 0:
key_ = Fernet.generate_key()
print(type(key_))
with open(self.key_path, "wb") as file:
file.write(key_)
file.close()
return key_
else:# Opening exist file
with open(self.key_path, "r") as file:
return file.readlines()[0]
在Python中将字节写入文件时,重要的是要确保文件以二进制模式打开并且写入的数据是字节格式。 这是如何完成的代码--
file_path = r'C:\Users
尝试:
with open(file_path, 'wb') as file:
file.write(data_to_write)
print("Bytes have been successfully written to the file.")
例外情况为 e: print("将字节写入文件时发生错误:", e)