首页 > 解决方案 > 如何避免将字典数据保存到文本文件中,从而导致在保存的文本文件中创建多个字典

问题描述

我正在尝试将一些用户输入以字典格式保存到文本文件中。问题在于,不是将数据保存为连续键值对格式,而是创建了多个字典。我怎样才能避免这种情况?

from pathlib import Path

username = input("Username: ")
password = input("Password: ")
my_dict = {username: password}
myfile = Path('sample.txt')
myfile.touch(exist_ok=True)

with open('sample.txt', 'a') as data:
   data.write(str(my_dict))

当前示例文本输出:

{'1': '1'}{'2': '2'}

预期输出:

{'1': '1','2': '2'}

标签: pythonpython-3.x

解决方案


解决方案:

您应该在程序中更改三件事。首先,如果使用该update方法,它将正确地将值添加到 中dict,其次使用 json 之类的序列化格式而不是文本文件,最后在写入文件时只需w使用dict

这是代码:

from pathlib import Path
import json

myfile = Path('sample.json')
myfile.touch(exist_ok=True)
#reading the file intoa dictionary
with open(myfile,'r') as file:
    my_dict = json.load(file)

#getting inputs
username = input("Username: ")
password = input("Password: ")
#adding the data as a continues key value format to the dict
my_dict.update({username : password})

#write the data to the json file in overwrite mode
with open(myfile,'w') as file:
   json.dump(my_dict, file)

文件输出:

{"1": "1", "2": "2"}

有关json在 python 中使用的更多信息,请参阅

注意 json 文件在程序第一次运行时应该有一个 {} 以防止错误


推荐阅读