【问题标题】:How do I change a text dictionary from file into usable dictionary如何将文本字典从文件更改为可用字典
【发布时间】:2020-07-14 15:32:14
【问题描述】:

没错,我需要制作这个函数,基本上将玩家的用户名保存在字典中,然后将其保存在文本文件中以再次重复使用。

问题在于重用它我无法将我从文件中获取的 str 获取到字典中。

这是我的代码:

from ast import eval

def verification(j, d):
    if j in d.keys():
        return d
    else:
        d[j] = [0,0]
    return d

savefile = open("save.txt", "r")
'''d = dict()
for line in savefile:
    (key, val) = line.split(".")
    d[key] = val
print(d)'''
d = savefile.read()
python_dict = literal_eval(d)
savefile.close()


j = input("name? ")
result = verification(j, python_dict)

savefile = open("save.txt", "w")
'''for i in result:
    text = i + "." + str(result[i]) + " \n"
    savefile.write(text)'''
savefile.write(str(result))
savefile.close()

如您所见,我尝试使用来自astliteral_eval。我也尝试做一个 .split() 但这行不通。所以我被困住了。有任何想法吗?会有很大帮助的。

谢谢

【问题讨论】:

  • “不起作用”——请提供完整的回溯。一般来说,您应该提供minimal reproducible example,包括重现您的问题所需的最小输入和代码——以及实际问题是什么。
  • 考虑改用json
  • @Tomerikoo 我的代码看起来如何?
  • @AryaMcCarthy 好吧,我将密钥及其值保存在由“。”分隔的文件中。会发生什么,当我做一条新线时,它会下降两个。因此会出现错误,因为没有任何东西可以拆分并制成单独的键和值
  • 你看过那个链接了吗?这非常简单。就像json.dump(result, savefile)python_dict = json.load(savefile) 一样简单

标签: python-3.x function file dictionary text


【解决方案1】:

如果您有现有的库可以为您完成编码/解码,则无需从头开始进行自己的编码/解码。

一个很好的例子是JSON,它也不是 Python 独有的,因此您创建的数据库可以被其他应用程序使用。

这可以通过以下方式轻松完成:

import json

def verification(j, d):
    if j not in d:
        d[j] = [0,0]
    return d

with open("save.txt", "r") as savefile:
    python_dict = json.load(savefile)

j = input("name? ")
result = verification(j, python_dict)

with open("save.txt", "w") as savefile:
    json.dump(result, savefile)

【讨论】:

  • 我运行了你的代码,它给了我一个错误:给我 5 个文件路径后它说:json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
  • 正如错误所说,JSON 使用双引号 "。如果您手动编写文件,请将单文件更改为双文件
  • 分享文件内容
  • 所以我在文本中添加了双引号,它可以工作,除了 python_dict 是一个字符串而不是字典,因此,我不能添加和更改它的键和值。
  • 文件包含:"{'Natsirt': [0, 0]}"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-20
  • 1970-01-01
  • 2020-03-26
  • 1970-01-01
  • 2019-07-17
  • 1970-01-01
相关资源
最近更新 更多