Skip to main content
 首页 » 编程设计

Python之将大型 CSV 文件转换为 JSON

2025年01月19日10pengyingh

我有一个 4.5GB 的 CSV 文件,我正尝试使用 Python 2.7 将其转换为 JSON。我可以在较小的 500mb 文件上正常工作,但是在较大的文件上内存不足。如何将我编码的内容转换为以 block 形式读取 CSV 文件并将其写入(以 block 形式追加)到 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') 

请您参考如下方法:

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

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')