4

我不知道如何使用 Python3 创建JSONL

test = [{'a': 'b'}, {'a': 'b'}, {'a': 'b'}]

with open("data.json", 'w') as f:
    for item in test:
        json.dump(item, f)

with open("data.json") as f:
    for line in f:
        // only 1 line here! 
        print(line)

// prints
{"a": "b"}{"a": "b"}{"a": "b"}

我试过使用缩进选项来转储,但它似乎没有什么不同,并且分隔符选项似乎不是一个很好的用例。不确定我在这里缺少什么?

4

1 回答 1

6

.write与换行符一起使用\n

前任:

import json
test = [{'a': 'b'}, {'a': 'b'}, {'a': 'b'}]

with open("data.json", 'w') as f:
    for item in test:
        f.write(json.dumps(item) + "\n")

with open("data.json") as f:
    for line in f:
        print(line)
于 2019-07-17T09:09:47.007 回答