How to incrementally write into a json file

前端 未结 3 1801
我在风中等你
我在风中等你 2021-02-07 20:05

I am writing a program, which requires me to generate a very large json file. I know the traditional way is to dump a dictionary list using json.dump()

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-07 20:55

    You could also assume you have an iterable it that you want to write out to a file handle fh as a large JSON array of records, and do the following, which I think is the most straightforward approach:

    def write_json_iter(it, fh):
        print("[", file=fh)
        for n, rec in enumerate(it):
            if n > 0:
                print(",", file=fh)
            json.dump(rec, fh)
        print("]", file=fh)
    

提交回复
热议问题