简体   繁体   English

试图从文本文件中读取字典

[英]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: 这是使用imp模块的hacky解决方案:

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. 由于您具有有效的python代码,因此最简单的方法就是直接导入它。 First rename your file from account.txt to account.py - or something similar, so long as it has the .py suffix. 首先将文件从account.txt重命名为account.py或类似的名称,只要后缀为.py

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}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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