python - 如何通过简单的文件读取加载 jsonlines 文件
问题描述
考虑有下面的代码和一个jsonl
文件,
有一个特定的原因我不使用jsonlines.open()
api 读取文件,所以请将此作为事实。
jsonlines 包的参考: https ://jsonlines.readthedocs.io/en/latest/#jsonlines.Reader
import jsonlines
with open('example.jsonl', 'r') as jsonl_f:
content = jsonl_f.read()
with jsonlines.Reader(content) as reader:
lst = [obj for obj in reader]
example.jsonl
内容:
{"hello": "world"}
{"covid": "19"}
我上lst=
线的错误:
lst = [obj for obj in reader]
File "../lib/python3.7/site-packages/jsonlines/jsonlines.py", line 204, in iter
skip_empty=skip_empty)
File "../lib/python3.7/site-packages/jsonlines/jsonlines.py", line 164, in read
six.raise_from(exc, orig_exc)
File "<string>", line 3, in raise_from
jsonlines.jsonlines.InvalidLineError: line contains invalid json: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) (line 1)
解决方案
import jsonlines
with jsonlines.open('example.jsonl', 'r') as jsonl_f:
lst = [obj for obj in jsonl_f]
jsonl_f是阅读器,可以直接使用。它包含 json 文件中的行。
推荐阅读
- jquery - 你如何在jquery中为一组div增加一个类
- c# - 破坏随机字符串
- java - 如何在 Android 上的 /0 处创建目录?
- awk - 如何删除文件夹中多个文件的“0”行?
- android - Android Chip_如何以编程方式使芯片背景颜色透明?
- r - 具有 Kolmogorov-Smirnov 双样本、Cramer-von Mises 和 Kuiper 检验的 ECDF
- c++ - C++ 标识符“读取”冲突?
- python - Pandas 已安装但无法识别
- android - 在华为应用程序库中使用一个 Signal Cordova Plugin SDK 支持 Android 应用程序
- c++ - 从 HANDLE 到 ULONG C++ 的类型转换截断