前言
大量文件分批读写
import ijson
import json
def json_to_jsonl_with_progress(in_file, out_file) :
with open(in_file, 'r', encoding='utf-8') as fin, \
open(out_file, 'w', encoding='utf-8') as fout :
for i, obj in enumerate(ijson.items(fin, 'item'), start=1) :
fout.write(json.dumps(obj, ensure_ascii=False) + '\n')
# ✅ 每50个输出一次
if i % 1000 == 0 :
print(f"已处理: {i}")
# 可选:最后不足50的补一次
print(f"完成,总计: {i}")
import json
import pandas as pd
DROP_KEYS = {"related", "desc_v2"}
def jsonl_to_df(in_file,DROP_KEYS) :
data = []
count = 0
with open(in_file, 'r', encoding='utf-8') as f :
for line in f :
obj = json.loads(line)
# ✅ 原地删除字段
for k in DROP_KEYS :
if k in obj :
del obj[k]
data.append(obj)
count += 1
# 每50条输出一次
if count % 1000 == 0 :
print(f"已处理: {count}")
print(f"完成,总计: {count}")
return pd.DataFrame(data)
def df_to_jsonl_stream(df, out_file) :
count = 0
with open(out_file, 'w', encoding='utf-8') as f :
for count, row in enumerate(df.itertuples(index=False), start=1) :
# 👉 每一行转 dict(等价于 list[dict] 里的一个元素)
obj = row._asdict()
# 👉 流式写入(一行一个 dict)
f.write(json.dumps(obj, ensure_ascii=False) + '\n')
if count % 1000 == 0 :
print(f"已处理: {count}")
print(f"完成,总计: {count}")
import json
def list_to_jsonl_stream(data_list, out_file):
"""
将 list 流式写入 JSONL 文件
Args:
data_list: 要写入的列表(每个元素是 dict)
out_file: 输出文件路径
"""
count = 0
with open(out_file, 'w', encoding='utf-8') as f:
for item in data_list:
# 直接写入 JSON 对象
f.write(json.dumps(item, ensure_ascii=False) + '\n')
count += 1
if count % 1000 == 0:
print(f"已处理: {count}")
print(f"完成,总计: {count}")