将数据附加到现有Json文件

问题描述 投票:0回答:1

我有以下格式的json文件:

{"CustomerNo": "858017D", "SalesOrder": "ERI2380", "Brand": "HONAC", "Item": "HL10CESWB", "Qty": "1", "Month": "6","time": "2018-06-19T16:28:58Z"}
{"CustomerNo": "072881D", "SalesOrder": "W619091", "Brand": "HONAC", "Item": "MO10CESWK", "Qty": "-1", "Month": "6","time": "2018-06-08T12:36:29Z"}
{"CustomerNo": "072881D", "SalesOrder": "W642501", "Brand": "HONAC", "Item": "MO08CESWK", "Qty": "1", "Month": "6",  "time": "2018-06-19T08:20:51Z"}
{"CustomerNo": "072866D", "SalesOrder": "W645370", "Brand": "HONAC", "Item": "MN10CESBB", "Qty": "1", "Month": "6",  "time": "2018-06-19T16:36:22Z"}

需要附加到具有类似格式的数据的现有文件。但是生成的文件变得混乱了。我需要每天多次附加此文件。代码如下:

csvfile1 = open('daily.csv', 'r')
jsonfile1 = open('test3.json', 'a')
fieldnames = list(raw_data.columns.values)
reader1 = csv.DictReader( csvfile1, fieldnames)


next(reader1)
jsonfile1.write('\n')
pos = next1 = 0
for row in reader1:
    pos = next1
    next1 += len(row) # compute position of beginning of next line
    json.dump(row, jsonfile1)
    jsonfile1.write('\n')
jsonfile1.truncate(pos)

最终输出并不完全是追加。它是一些带有不完整json对象的格式错误的文件。

python
1个回答
1
投票

完成后考虑关闭文件(或使用-as)。也不确定为什么要计算在追加结尾处截断(在'a'模式下)的位置。

import csv
import json

fieldnames = ("CustomerNo", "SalesOrder", "Brand", "Item", "Qty", "Month", "time")

# Handle the case when there is no newline at the end. Format a file before appending.

with open('daily.csv', 'r') as csvfile1:
    with open('test3.json', 'a') as jsonfile1:
        for row in csv.DictReader(csvfile1, fieldnames):
            json.dump(row, jsonfile1)
            jsonfile1.write('\n')
© www.soinside.com 2019 - 2024. All rights reserved.