簡體   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