python - 字典到字符串不作为字典读回

标签 python dictionary

由于 Json 和 Pickle 方法不起作用,我决定将字典保存为字符串,这可行,但它们没有被读取。

IE

字典

a={'name': 'joe'}

保存:

file = open("save.txt", "w")
file.write(str(a))
file.close()

这有效。 但我的加载方法没有读取它。

负载:

f = open("save.txt", "r")
a = f
f.close()

所以,它只是不会变成f。 我真的不想使用 json 或 pickle,有什么办法可以让这个方法工作吗?

最佳答案

首先,您实际上并没有从文件中读取任何内容(文件不是其内容)。其次,当你解决这个问题时,你将得到一个字符串并需要将其转换为字典。

幸运的是,这两个问题都很容易解决......

from ast import literal_eval

with open("save.txt") as infile:
    data = literal_eval(infile.read())

关于python - 字典到字符串不作为字典读回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37103447/

相关文章:

python - 使用 pandas 将带有填充零的序列号附加到序列中

python - 当列名包含空格时删除多列 pandas

python - 如何在 Python 中习惯性地对嵌套字典键进行排序

python - 生成具有多个列的.CSV-使用字典吗?

c - 如何在 C 中存储我的 map ?

python - python格式字符串中的 'h'是什么意思?

Python Pip 安装 SSL 错误 749

python - 多次将相同的内容写入文本文件

Python 字典 : TypeError: list indices must be integers, 不是 str

python:迭代不断变化的字典