仅使用Python写入JSON对象的特定部分
我似乎不明白如何只写JSON对象的特定部分 下面显示了对象(现实中会有更多的用户) 对于每个用户,我只想将“required”、“blocked”、“缺席”和“preference”更改为指定变量的值(对于每个人,“required”…“缺席”都是不同的。有没有办法做到这一点仅使用Python写入JSON对象的特定部分,python,json,python-3.x,Python,Json,Python 3.x,我似乎不明白如何只写JSON对象的特定部分 下面显示了对象(现实中会有更多的用户) 对于每个用户,我只想将“required”、“blocked”、“缺席”和“preference”更改为指定变量的值(对于每个人,“required”…“缺席”都是不同的。有没有办法做到这一点 适用于范围内的人员(totalUsers): 所需=分配天数(O) 阻塞=分配天数(R) 缺席天数(A) 首选项=首选项天数() 以open('TestScript.json','a')作为输出文件: 数据={“用户”:{
适用于范围内的人员(totalUsers):
所需=分配天数(O)
阻塞=分配天数(R)
缺席天数(A)
首选项=首选项天数()
以open('TestScript.json','a')作为输出文件:
数据={“用户”:{
“姓名”:[],
“偏好”:偏好,
“团队”:“x”,
“封锁”:封锁,
“必需”:必需,
“缺席”:缺席}
json.dump(数据,输出文件)
outfile.write(“\n”)
JSON是数据结构的文本表示。要获得所需的内容,只需将文本文件中的数据加载到数据结构中,修改数据结构,然后将新修改的结构写回文本文件
# Read the data from the text file into a python dictionary
data = json.load(outfile)
# Create a new dictionary, starting with the original one and overriding
# whatever values you want to change. You could also do a series of
# data["required"] = "new value"
# lines instead (if you prefer)
updated_data = dict(data, requied=required, blocked=blocked, ...)
# now that we have a new dictionary with the data that we want in it,
# write it to a text file
json.dump(data, outfile)
JSON是数据结构的文本表示。要获得所需的内容,只需将文本文件中的数据加载到数据结构中,修改数据结构,然后将新修改的结构写回文本文件
# Read the data from the text file into a python dictionary
data = json.load(outfile)
# Create a new dictionary, starting with the original one and overriding
# whatever values you want to change. You could also do a series of
# data["required"] = "new value"
# lines instead (if you prefer)
updated_data = dict(data, requied=required, blocked=blocked, ...)
# now that we have a new dictionary with the data that we want in it,
# write it to a text file
json.dump(data, outfile)
你似乎没有使用
required
或blocked
,而且days\u required
和days\u blocked
都是未定义的。啊,好棒的spot Scott!我做了一些编辑来简化它,但显然没有用!你似乎没有使用required
或blocked
,以及days\u required
和days\u blockedd
未定义。啊,太棒了,斯科特!我做了一些编辑来简化它,但显然不起作用!我真的很抱歉,请您再解释一下,我不确定我是否完全理解这是如何工作的。感谢您可能需要输出文件。截断(0)
要在将修改后的数据转储到旧文件之前清除旧文件,可能-我已经使用Path.read_text()和Path.write_text()有一段时间了,不记得其语义。非常抱歉,请您再解释一点,我不确定我是否完全理解这是如何工作的。感谢可能需要outfile.truncate(0)
要在将修改后的数据转储到它之前清除旧文件,可能-我已经使用Path.read_text()和Path.write_text()有一段时间了,不记得语义了。