Why are my bytes not being written to my file?

Question:

I’m making a system, where you take a string, encrypt it, and write to a file. Here is how I do it:

data = "My secret data!"
datastoreName = "Datastore"
datastore = open(datastoreName + ".txt", "wb")
from cryptography.fernet import Fernet
key = Fernet.generate_key()
fernet = Fernet(key)
encData = fernet.encrypt(data.encode())
datastore.write(encData)

Whenever I run it, nothing gets to written the datastore.txt, and there is no errors shown. What am I doing wrong, and how can I fix it?

Asked By: gamer merch

||

Answers:

I think the issue you are having is related to you not closing the file. When you write/read a file in python, you should use a context manager. Basically, it closes the file once you are done using it. What you did was open the file, then left the file open and the script ended so Python never actually saved anything to the file. In fact, it can sometimes be dangerous to not close files since in more complicated programs it can cause corruption. What you should probably do using a context manager is:

from cryptography.fernet import Fernet

data = "My secret data!"
datastoreName = "Datastore"
key = Fernet.generate_key()
fernet = Fernet(key)
encData = fernet.encrypt(data.encode())

with open(datastoreName + ".txt", "wb") as datastore:
  datastore.write(encData)

The with statement automatically closes the file after you are done editing it. Note that anything not indented under the with statement will not edit the file.

Answered By: Alan Shiah
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.