Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将数据附加到现有Json文件_Python - Fatal编程技术网

Python 将数据附加到现有Json文件

Python 将数据附加到现有Json文件,python,Python,我有以下格式的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"

我有以下格式的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对象不完整。

请考虑在完成(或与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')

正在截断在文件末尾创建的新行。不管怎么说,这个解决办法奏效了。Thanks@AbhishekKumar若并没有首先截断,那个么在追加到文件之前就不需要添加新行了(就像你们做的那个样)。