Getting error while writing bytes to file?

135 views Asked by At

I am working on a tkinter projects which save encrypted passwords. I am writing key to this path: C:\Users\<usrname>\.PassManager\PassManager.key.

It was working fine, all of sudden I do not what happened I am getting this error. While writing I have mentioned to write bytes to file. It doesn't seems working.

Understanding:

Error: 'bool' object

self.key_path() is not a boolean variable?

What is the cause of this problem?

Error:

<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

Code:

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]
2

There are 2 answers

3
SIGHUP On BEST ANSWER

Somewhere in your code you've overridden/shadowed the built-in open function with some callable that returns either True or False

Here are some examples that would lead to the exception you're observing:

# 1st possibility
def open():
    return True

# 2nd possibility
open = lambda: False

# 3rd possibility
def banana():
    return True

open = banana

# Then...
with open() as _:
    ...

...leads to...

TypeError: 'bool' object does not support the context manager protocol
1
Rudra Tiwari On

When writing bytes to a file in Python, it's important to ensure that the file is opened in binary mode and that the data being written is in bytes format. here the code how it is done--

file_path = r'C:\Users\<usrname>\.PassManager\PassManager.key'
data_to_write = b'your_bytes_data_here'

try:
   
    with open(file_path, 'wb') as file:
       
        file.write(data_to_write)
        print("Bytes have been successfully written to the file.")
except Exception as e:
    print("An error occurred while writing bytes to the file:", e)