导入和导出字典 from/to 文件 - 没有 json 或模块

Import and export dictionary from/to file - no json or modules

我想将我的词典保存到一个文件中,以便以后可以轻松导入它并保持其词典含义。如果我执行以下操作:

def save_dict_to_file(dic):
    f = open('dict.txt','w')
    f.write(str(dic))
    f.close()

然后,如果我想从文件中加载字典,请执行以下操作:

d={}
fi=open("dict.txt","r")
lineinfile=fi.readlines()
d=lineinfile
print(type(d))

我得到的结果是一个列表,而不是字典。 不使用任何模块,如何解决?是我导出字典时出错还是导入时出错?

您可以使用标准库中的json

import json

data = {'a': 1, 'b': 2}

# Save data
with open('output_name.json', 'w') as f:
    json.dump(data, f)

# Read data
with open('output_name.json', 'r') as f:
    data = json.load(f)

如果你想自己做(没有 json 模块),那就没那么简单了。您可以查看 json 源代码它是如何完成的 https://github.com/python/cpython/tree/3.9/Lib/json

您正在使用 readlines() 函数,其中 returns 包含文件中每一行的列表作为列表项