2

I am creating a application where I have a Dictionary (which is produced from a specific cryptography algorithm) variable and save it to a text file. I retrieve the variable and convert it to Dictionary again like this:

f = open( '/sk.txt')
t_ref = f.read()
requested_encrypted_file = ast.literal_eval(t_ref)
print type(requested_encrypted_file)
f.close()

The Dictionary variable which contain the vital infos for the ciphertext has this form:

{'msg': '{"ALG": 0, "CipherText": "xcUHHV3ifPJKFqB8aL9fzQ==", "MODE": 2, "IV": "2Y2xDI+a7JRt7Zu6Vtq86g=="}', 'alg': 'HMAC_SHA1', 'digest': '4920934247257f548f3ca295455f5109c2bea437'}

The problem is that when I retrieve this variable from file all the fields are str and not the type they where before save it to a txt file? Is there a simple way to retrieve them with the correct types?

Any advice would be helpful and deeply appreciated.

Amir
  • 10,600
  • 9
  • 48
  • 75
PL13
  • 393
  • 2
  • 5
  • 13
  • How do you save the dictionary to the file? – Mark Tolonen Jan 03 '16 at 19:23
  • Like this: f = open('/sk.txt', 'w' ) f.write(str(ciphertext)) f.close() – PL13 Jan 03 '16 at 19:29
  • If `ciphertext` contains the value you've shown, all the keys and values *are* strings. Do you want the value type of key `msg` to be `dict`? If so, the problem is generating the value being written to the file. Your code works as is if you remove the single quotes around msg's value. – Mark Tolonen Jan 03 '16 at 19:30

2 Answers2

3

If you only have to deal with basic data types, save and load your data JSON-serialized.

import json

a = {'foo': 'bar', 'baz': 42, 'biz': True}

# Save
with open('test.txt', 'w') as outf:
    json.dump(a, outf)

# Read
with open('test.txt', 'r') as inf:
    b = json.load(inf)

b will be

{'baz': 42, 'biz': True, 'foo': 'bar'}

karlson
  • 5,325
  • 3
  • 30
  • 62
2

I would use the pickle module to dump Python data structures as serializable data and then load.

pickle.dump(dictionary, open('data.p', 'w')) # write file with dictionary structure
savedData = pickle.load(open('data.p', 'r')) # reads the written file as dictionary
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70