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?
CodePudding user response:
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.