簡體   English   中英

將數據追加到現有的Json文件

[英]Appending data to an existing Json file

我有以下格式的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對象。

完成后考慮關閉文件(或使用with-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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM