【问题标题】:Python - Converting large CSV file to JSONPython - 将大型 CSV 文件转换为 JSON
【发布时间】:2018-07-14 18:39:09
【问题描述】:

我有一个 4.5GB 的 CSV 文件,我正在尝试使用 Python 2.7 将其转换为 JSON。我可以使用较小的 500mb 文件正常工作,但是较大的文件内存不足。如何将我编码的内容转换为以块的形式读取 CSV 文件并将(以块的形式附加)写入 JSON 文件的内容?

f = open('table-52007-changeset.csv', 'rb' )
reader = csv.DictReader(f) 

out = json.dumps( [ row for row in reader ] )  
json_response = json.loads(out)

jsonoutput = 'masterlist2.0.json'
with open(jsonoutput, 'a') as f:
    for x in json_response: 
        json.dump(x,f)
        f.write('\n')

【问题讨论】:

  • 为什么会有 dump、load、dump 跳舞?

标签: python json python-2.7 csv


【解决方案1】:

您当前正在使用以下行将整个结构读入内存:

out = json.dumps( [ row for row in reader ] )  

而是一次一行地直接进入json,例如:

import json
import csv

with open('table-52007-changeset.csv', 'r') as input_file:
    reader = csv.DictReader(input_file)

    jsonoutput = 'masterlist2.0.json'
    with open(jsonoutput, 'a') as output_file:
        for row in reader:
            json.dump(row, output_file)
            f.write('\n')

【讨论】:

    猜你喜欢
    • 2017-01-29
    • 1970-01-01
    • 2013-09-16
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2015-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多