简体   繁体   中英

Trying to read dictionary from text file

I have a text file having dictionaries like this -

account1 = {'email':'abc@test1', 'password':'abc321', 'securitycode':546987, 'name':'tester1', 'phone':236945744 }

account2 = {'email':'abc@test2.com', 'password':'abc123', 'securitycode':699999, 'name':'tester2', 'phone':666666666666 }

and I'm trying to read these dictionaries value with this code -

dicts_from_file = []
with open('account.txt','r') as inf:
  dict_from_file = eval(inf.read())


print (dicts_from_file)

but i get this traceback-

Traceback (most recent call last):
File "C:\Python\Dell_test.py", line 15, in <module>
dict_from_file = eval(inf.read())
File "<string>", line 2
{'email':'abc@test2.com', 'password':'abc123', 'securitycode':699999, 
'name':'tester2', 'phone':666666666666 }
^
SyntaxError: invalid syntax

Can anybody please help and guide whats wrong with this snippet?

Here is hacky solution, using imp module:

import imp

accounts = imp.load_source('accounts', 'account.txt')

from accounts import *

print(accounts1)
# {'email':'abc@test1', 'password':'abc321', 'securitycode':546987, 'name':'tester1', 'phone':236945744 }

But, for future, i would suggest to you not to use this file format)

As others have said, you should use a serialisation format, but assuming that is not under your control, there are hacky ways to do this.

Since you have valid python code, the simplest way is to just import it. First rename your file from account.txt to account.py - or something similar, so long as it has the .py suffix.

If you just imported the module then you would not know the account names, assuming these are random and you need to retain them. He is a way to get them into a list:

import account

dicts_from_file = [account.__dict__[i] for i in dir(account) if not i.startswith("__")]
print(dicts_from_file)

Possibly more useful, into a dictionary where the account names are the keys:

import account
import pprint

dict_names = [i for i in dir(account) if not i.startswith("__")]
dicts_from_file = {i:account.__dict__[i] for i in dict_names}
pprint.pprint(dicts_from_file)

Gives:

{'account1': {'email': 'abc@test1',
              'name': 'tester1',
              'password': 'abc321',
              'phone': 236945744,
              'securitycode': 546987},
 'account2': {'email': 'abc@test2.com',
              'name': 'tester2',
              'password': 'abc123',
              'phone': 666666666666,
              'securitycode': 699999}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM