【问题标题】:Converting a large CSV file to multiple JSON files using Python使用 Python 将大型 CSV 文件转换为多个 JSON 文件
【发布时间】: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 文件。

我该怎么做?

【问题讨论】:

    标签: python json csv


    【解决方案1】:

    拆分你的读\写方法并添加一个简单的阈值:

    JSON_ENTRIES_THRESHOLD = 5000  # modify to whatever you see suitable
    
    def write_json(json_array, filename):
        with open(filename, 'w', encoding='utf-8') as jsonf: 
            json.dump(json_array, jsonf)  # note the usage of .dump directly to a file descriptor
    
    def csv_to_json(csvFilePath, jsonFilePath):
        jsonArray = []
    
        with open(csvFilePath, encoding='utf-8') as csvf: 
            csvReader = csv.DictReader(csvf) 
            filename_index = 0
        
            for row in csvReader:
                jsonArray.append(row)
                if len(jsonArray) >= JSON_ENTRIES_THRESHOLD:
                    # if we reached the treshold, write out
                    write_json(jsonArray, f"jsonFilePath-{filename_index}.json")
                    filename_index += 1
                    jsonArray = []
                
            # Finally, write out the remainder
            write_json(jsonArray, f"jsonFilePath-{filename_index}.json")
    
    

    【讨论】:

    • 喜欢答案,但为了便于阅读,我会将write_json 函数放在 if 条件中,而不是使用 continue
    • 是的,这样会更好
    • @gionni,我还修复了覆盖问题-所有文件都以相同的名称记录。
    猜你喜欢
    • 2018-07-14
    • 1970-01-01
    • 2017-01-29
    • 2019-01-04
    • 2019-03-25
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2022-09-23
    相关资源
    最近更新 更多