【问题标题】:How to solve memory error when loading 1GB large json files in python?在 python 中加载 1GB 大 json 文件时如何解决内存错误?
【发布时间】:2016-05-04 13:11:30
【问题描述】:

我正在尝试将 json 文件转换为 csv,但出现内存错误。 是否有任何有效的方法来微调此代码以在 python 中处理大型 json 文件。

def change(row, pastkeys=()):
result = {}
c=0
for key in row:
    c=c+1
    newkey = pastkeys + (key,)
    print key
    val = row[key]
    if isinstance(val, dict):
        result.update(change(val, newkey))
    elif isinstance(val, list):
        result.update(change(dict(zip(range(0, len(val)), val)), newkey))
    else:
        result[newkey] = val
return result
a=open(sys.argv[1],'r')
lines=list(a)
 print lines
out1=open(sys.argv[2],'w')
try:
  data = json.loads(''.join(lines))
  if isinstance(data, dict):
    data = [data]
  except ValueError:
    data = [json.loads(line) for line in lines]
 result = []
 fields = set()
 for row in data:
    hash = change(row)
    fields |= set(hash.keys()
    result.append(hash)
out1=open(sys.argv[2],'w+')
fields = sorted(fields)
out = csv.writer(out1,lineterminator='\n')
out.writerow(['-'.join([str(f) for f in field]) for field in fields])
for row in result:
out.writerow([(row.get(field,'')) for field  in fields ])

a.close()

【问题讨论】:

  • 错误是什么?异常或被操作系统杀死的进程?
  • 请修正你的缩进

标签: python csv io out-of-memory


【解决方案1】:

您可以尝试使用ijson。它是一个将 JSON 作为流而不是块文件使用的模块。 ijson 之于 JSON 就像 SAX 之于 XML。

import ijson
for prefix, theType, value in ijson.parse(open(jsonFileName)):
    print prefix, theType, value

【讨论】:

    【解决方案2】:

    您正在将文件的全部内容加载到一个列表(行)中,并将结果存储在另一个列表中(结果)。

    除非您需要一些优势,例如访问速度(ram vs hdd),否则不要将文件的全部内容加载到内存中。

    相反,您可以一次处理一行,读取、处理并附加到您的文件中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-09
      • 1970-01-01
      • 2013-04-12
      • 2021-06-09
      相关资源
      最近更新 更多