【发布时间】:2021-02-16 19:34:46
【问题描述】:
我目前正在使用以下代码将大型 CSV 文件转换为 JSON 文件。
import csv
import json
def csv_to_json(csvFilePath, jsonFilePath):
jsonArray = []
with open(csvFilePath, encoding='utf-8') as csvf:
csvReader = csv.DictReader(csvf)
for row in csvReader:
jsonArray.append(row)
with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
jsonString = json.dumps(jsonArray, indent=4)
jsonf.write(jsonString)
csvFilePath = r'test_data.csv'
jsonFilePath = r'test_data.json'
csv_to_json(csvFilePath, jsonFilePath)
这段代码运行良好,我可以毫无问题地将 CSV 转换为 JSON。但是,由于 CSV 文件包含 600,000 多行,因此我的 JSON 中的项目也很多,因此管理 JSON 文件变得非常困难。
我想修改上面的代码,以便每 5000 行 CSV 将数据写入一个新的 JSON 文件。理想情况下,在这种情况下,我将拥有 120 (600,000/5000) 个 JSON 文件。
我该怎么做?
【问题讨论】: