高效率地保存多个 Python 对象!你学会了吗?

json文件因其简洁精炼,在网上特别流行,我们写爬虫时经常碰到网站使用json格式传输数据。但是如果要存储的数据有1G,那么读取一个json文件需要一次性读入,这需要占用很大的内存,对电脑压力过大。所以我们需要将数据存储为很多个对象,通过逐行读取方式减轻内存占用压力。所以今天就讲到jsonlines这个库,希望大家能有所收获。

jsonlines

  • 每一行都是一个json或python对象
  • 采用utf-8编码

jsonlines库的特性

便捷的open()功能

  • 易于写入
  • 传入文件名和写入方式mode
  • 返回Reader或Writer实例
  • 能被用做上下文管理器

安装

pip install jsonlines

使用方法

jsonlines可以保存python的各种数据类型对象,如列表、字典、数字、元组、集合等等。

例如以python字典类型逐行写入到jsonl文件里

加群:960410445   一起学习一起交流!

import jsonlines
with jsonlines.open('data.jsonl', mode='w') as writer:
 writer.write({'a':5})
 writer.write({'a':6})
 writer.write({'a':7})

发现当前工作路径下已经生成了一个jsonl文件。

以逐行的方式读取jsonl文件里的多个字典

with jsonlines.open('data.jsonl', mode='r') as reader:
 for row in reader:
 print(type(row), row)

运行

<class 'dict'> {'a': 5}
<class 'dict'> {'a': 6}
<class 'dict'> {'a': 7}

猜你喜欢

转载自blog.csdn.net/qq_42156420/article/details/85321001