【问题标题】:How to append to a json file on the fly?如何即时附加到 json 文件?
【发布时间】:2016-12-01 05:58:04
【问题描述】:

我正在解析数千个作为 dict 输出的 html 文件。然后我想将它们组合为一个字典并以 json 格式保存到磁盘。

我不想在遍历文件时在内存中构建这个巨大的字典,我宁愿在进行过程中不断更新/写入文件。

所以不要这样:

data = {}
for e, fn in enumerate(os.listdir(path)):
    fp = os.path.join(path, fn)
    d = html_to_dict(fp)
    data[e] = d

我想要这个:

with open('out_file.json', 'w') as f:
    for e, fn in enumerate(os.listdir(path)):
        fp = os.path.join(path, fn)
        d = html_to_dict(fp)
        # update the file dict

有什么想法吗?

【问题讨论】:

    标签: python json file dictionary


    【解决方案1】:

    您应该能够通过自己编写一些 JSON 并仅将 json 库用于单个记录来实现此目的。例如:

    with open('out_file.json', 'w') as f:
        f.write("{")
        delim = ""
        for e, fn in enumerate(os.listdir(path)):
            fp = os.path.join(path, fn)
            d = html_to_dict(fp)
            f.write(delim + str(e) + ":")
            json.dump(d, f)
            delim = ",\n"
        f.write("}")
    

    在这种情况下,您可以编写一个数组而不是一个对象,并节省键所需的空间:

    with open('out_file.json', 'w') as f:
        f.write("[")
        delim = ""
        for fn in os.listdir(path):
            fp = os.path.join(path, fn)
            d = html_to_dict(fp)
            f.write(delim)
            json.dump(d, f)
            delim = ",\n"
        f.write("]")
    

    【讨论】:

      猜你喜欢
      • 2013-08-08
      • 1970-01-01
      • 2020-09-18
      • 2012-10-11
      • 2019-12-29
      • 2020-05-03
      • 2018-11-17
      • 2014-04-03
      相关资源
      最近更新 更多