python - 如何避免将字典数据保存到文本文件中,从而导致在保存的文本文件中创建多个字典
问题描述
我正在尝试将一些用户输入以字典格式保存到文本文件中。问题在于,不是将数据保存为连续键值对格式,而是创建了多个字典。我怎样才能避免这种情况?
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'}
解决方案
解决方案:
您应该在程序中更改三件事。首先,如果使用该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 文件在程序第一次运行时应该有一个 {} 以防止错误
推荐阅读
- c - 如何编写一个程序,使用 scanf() 读取 2 个浮点数,其中包括求和、差、乘积、除法和平均值?
- java - Hibernate 多表查询性能
- groovy - 是否可以使用 groovy 脚本将字符串从 US-ASCII 转换为 UTF-8 编码?
- spring - 在表单提交时替代隐藏元素
- c# - MVC5 .NET 应用程序并获取当前用户名
- angularjs - 如何访问视图中降级组件的实例?
- sql-server - 在 VB.NET 标签上显示来自 SQL Server 的值
- python - 能够读取一个文件但无法将文件夹中的多个 json 文件读取到 padas 数据帧中
- r - 如何让倒计时在 R 中运行
- java - 如何从 .txt 或 .xslx 每 X 秒打开一个网页并自动下载文件提示