Reputation: 39
I am currently stuck on a project where I need to randomly create a dictionary to encrypt a file. Then reversing the key and the value of the dictionary to decrypt the file.
What I am doing now is that I'm saving the original dictionary to a file and afterwards want to be able to read from that file to get the dictionary, run it through the "reverse" function and therefore be able to decrypt the file.
Why I have decided on this approach is to not generate a new dictionary every single time I want to encrypt something.
I currently have this code written, this checks if there is a file with a saved dictionary. If there isn't then I create one so there is one:
def create_random_dictionary():
key = c.create_encryption_dictionary()
if os.path.exists("encryption_key"):
pass
else:
with open("encryption_key", 'w') as file:
file.write(str(key))
Then I try to read it go be able to use the dictionary. But since I am having to save it as a string when writing to file and not as a dictionary I can't use it properly to decrypt or encrypt.
Is there a way I can read the input file to then convert the read string back into a dictionary. I have tried with literal_eval like this
def string_to_dictionary():
with open('encryption_key', 'r') as f:
read_lines = f.readlines
x = literal_eval(read_lines)
print(x) # why I'm assigning x and printing x is just to see if it works
But I get an error like this:
File "/usr/lib/python3.6/ast.py", line 84, in _convert
raise ValueError('malformed node or string: ' + repr(node))ValueError: malformed node or string: ['{\'0\': \'ö\', \'1\': \'z\', \'2\': \'-\'
My main concerns is, how can I get rid of the extra "\" and then how can I read the string back and convert it to a dictionary.
Thankful for any help I can get.
Upvotes: 0
Views: 42
Reputation: 168967
str()
is not always reversible. It just so happens that for dicts it usually is.
If your data is JSON encodable (most likely is), use the json
module instead. (If it's, not use pickle
but heed the module's documentation's warnings.)
import json
def create_random_dictionary():
key = c.create_encryption_dictionary()
with open("encryption_key.json", 'w') as file:
json.dump(key, file)
return key
def read_dictionary():
with open('encryption_key.json', 'r') as file:
return json.load(file)
Upvotes: 1
Reputation: 1447
You can just join
the list
returned by readlines
, which solved the exact same problem I had when running something similar to your code:
with open('encryption_key', 'r') as f:
x = literal_eval(''.join(f.readlines()))
Upvotes: 1