繁体   English   中英

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

[英]Trying to read dictionary from text file

我有一个包含这样的字典的文本文件-

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 }

我正在尝试使用此代码读取这些字典值-

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


print (dicts_from_file)

但是我得到了这个追溯-

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

有人可以帮助和指导此代码段出什么问题吗?

这是使用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 }

但是,为了将来,我建议您不要使用此文件格式)

就像其他人所说的那样,您应该使用序列化格式,但是假设这种格式不受您的控制,则有很多方法可以做到这一点。

由于您具有有效的python代码,因此最简单的方法就是直接导入它。 首先将文件从account.txt重命名为account.py或类似的名称,只要后缀为.py

如果您只是导入模块,则假设这些帐户名是随机的,并且您需要保留它们,那么您将不知道该帐户名。 他是将他们列入清单的一种方法:

import account

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

可能更有用的是进入以帐户名称为键的字典:

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)

给出:

{'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