将数据存储在Json中,使用新数据进行更新并检索单个密钥(索引密钥,并且需要针对每个更新进行更新)

时间:2018-02-17 18:43:46

标签: python arrays json list dictionary

我想做的是: 将数据存储在JSON文件中,然后存储一次,程序结束

Process finished with exit code 0

我希望能够第二次运行程序并在同一个JSON文件中存储新数据,检索索引(从我存储的第一批数据)中添加+1以创建新数字,并且将第二组数据存储在同一个文件中,依此类推

这是我的代码:

from datetime import*
import json

#values and while loop to create the batch number

today=date.today()

componentNumber=int(input("Please input a number: "))
nCompWhile=componentNumber

types=(input("Please input types: "))

sizemodel=(input("Please input a size model: "))



index = 1
serialNList=[]

while nCompWhile > 0:
    serialNList.append(today.strftime("%d%m%Y") +
                       "{0:04}".format(index) + " - "
                       + "{0:04}".format(nCompWhile))
    nCompWhile -= 1

i = 0
compStatus = []
for element in serialNList:
    compStatus.append(serialNList[i] + " : unfinished work")
    i += 1

#The def should compare the the index with the index stored before 

def uniqueBatchN(x):
    if x == data["batch number"]:
        x = today.strftime("%d%m%Y") + "{0:04}".format(index+1)
        return x
    else:
        x= today.strftime("%d%m%Y")+ "{0:04}".format(index)
        return x

x= today.strftime("%d%m%Y")+ "{0:04}".format(index)

data={}

data["record"]=[]
data["record"].append({
    "batch number":x,
    "component type": types,
    "component size/fitment type": sizemodel,
    "components number in batch": str(componentNumber),
    "serial sumbers": str(serialNList[::-1]),
    "component status": str(compStatus[::-1]),
})
with open('data.json','w') as outfile:
    json.dump(data,outfile)

with open('data.json') as json_file:
    data = json.load(json_file)
    for p in data['record']:
        print("Batch Number: "+ p["batch number"])
        print("Component Type: "+ p["component type"])
        print("Component size/fitment type: "+ p["component size/fitment type"])
        print("Number of components in batch: "+p["components number in batch"])
        print("Serial Numbers: "+ p["serial sumbers"])
        print("Component status: "+ p["component status"])

但结果是它继续更新JSON文件,删除之前存储的密钥的值,同时索引不会使用新的"批号"更新。 这是输出:

Please input a number: 3
Please input types: type
Please input a size model: mode
Batch Number: 170220180001
Component Type: type
Component size/fitment type: mode
Number of components in batch: 3
Serial Numbers: ['170220180001 - 0001', '170220180001 - 0002', '170220180001 - 0003']
Component status: ['170220180001 - 0001 : unfinished work', '170220180001 - 0002 : unfinished work', '170220180001 - 0003 : unfinished work']

第二次输出:

Please input a number: 2
Please input types: mode
Please input a size model: type
Batch Number: 170220180001
Component Type: mode
Component size/fitment type: type
Number of components in batch: 2
Serial Numbers: ['170220180001 - 0001', '170220180001 - 0002']
Component status: ['170220180001 - 0001 : unfinished work', '170220180001 - 0002 : unfinished work']

1 个答案:

答案 0 :(得分:0)

直接回答你的问题,这一点:

with open('data.json','w') as outfile:
    json.dump(data,outfile)

以“写入”模式打开文件,即文件的任何输入都将覆盖文件中可能存在的任何内容,因此您每次运行后都只能查找最新记录。

您想要的是以'追加'模式打开文件:

with open('data.json','a') as outfile:
    json.dump(data,outfile)

参考:https://docs.python.org/3.6/tutorial/inputoutput.html#reading-and-writing-files

现在请记住,您的代码有更多问题,至少不是在列表括号外添加json对象(并且没有逗号分隔符)会导致无效的json,从而导致json.load崩溃。