【发布时间】:2016-04-08 09:03:00
【问题描述】:
我的代码涉及以字典的形式导入和导出用户名和密码。为了导出字典,我将其更改为字符串。 这是导入的文本文件(与导出代码的格式相同):
{'account1': 'password'}{'account2': 'password'}
要导出的代码如下:
accounts=open("accounts.txt","r")
accounts=accounts.read()
newaccount={username:password}#user name and password are user defined
str1=str(newaccount)
updated=open("accounts.txt","w")
updated.write(accounts)
updated.write(str1)
updated.close()
我希望字典看起来像这样:
{'account1':'password', 'account2':'password'}
【问题讨论】:
-
为什么不以更易于解析的格式导出字典?
-
我建议您使用
json对象来保存您的字典,因为这样您将无法轻松地从文件中读取它 -
将文本转换为列表并从列表中更新字典。
-
您介意提供一个您尝试导出到字典中的文本示例吗?
标签: python string dictionary type-conversion