在进行大量数据读写时,一般json不能读写特别大的数据,此时需要按行来进行读写:
# 按行写文件
import json
data = [
{'id': '123456', 'text': ' python'},
{'id': '456789', 'text': ' java'}
]
for item in data:
with open('data.json', 'a+', encoding='utf-8') as f:
line = json.dumps(item, ensure_ascii=False)
f.write(line+'\n')
# 按行读取文件
import json
data = []
with open('data.json', 'r', encoding="utf-8") as f:
# 读取所有行 每行会是一个字符串
for j in f.readlines():
print(j)
print(type(j))
# 将josn字符串转化为dict字典
j = json.loads(j)
print(type(j))
data.append(j)
print(data)
{"id": "123456", "text": " python"}
<class 'str'>
<class 'dict'>
{"id": "456789", "text": " java"}
<class 'str'>
<class 'dict'>
[{'id': '123456', 'text': ' python'}, {'id': '456789', 'text': ' java'}]