【问题标题】:Store data in Json, update with new data and retrieve a single key (index key and needs to be update for each update)将数据存储在 Json 中,用新数据更新并检索单个键(索引键,每次更新都需要更新)
【发布时间】:2018-02-17 18:43:45
【问题描述】:

我想做的是: 将数据存储在 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']

【问题讨论】:

    标签: python arrays json list dictionary


    【解决方案1】:

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

    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 崩溃。

    【讨论】:

    • Antoine M. 你能说得更具体点吗?
    • 如果你的意思是关于我的最后一段,你正在一个接一个地编写 json 对象,例如 {"key": "value"}{"key": "value"}。当您尝试使用 json.load 加载它们时会中断,因为它们需要在这样的列表中结构化: [{"key": "value"}, {"key": "value"}]
    猜你喜欢
    • 2019-02-16
    • 2022-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 2016-01-19
    • 2019-01-27
    相关资源
    最近更新 更多