使用 yield 流式传输到 JSON 文件

Stream to JSON file using yield

我有一个读取文件的函数,该文件在每次迭代后读取块和 return 以下内容。

def foo_now():
    for file in all_files:
        key_id, final_text = readChunk(file)
        yield {
            key_id : {
                'desc': final_text
            }
        }

早些时候,我将所有这些 returned 字典存储到一个字典中,然后他们将整个字典转储到一个 JSON 文件中,使用:

def foo_earlier():
    temp_dict = dict()
    for file in all_files:
        key_id, final_text = readChunk(file)
        temp_dict.update({key_id : {'desc': final_text}})
    return temp_dict

def saveJSON(filename, data):
    with open(filename, 'wb') as outfile:
        json.dump(data, outfile)
    print "Data saved in " + filename

saveJSON("file.json", foo_earlier())

但现在我想在使用 foo_now() 从文件中读取每个字典时将其逐一转储。我应该怎么做?

for item in foo_now():
    with open("my_out.json","ab") as f:
        json.dump(item,f)

with open("my_out.json","ab") as f:
    for item in foo_now():
        json.dump(item,f)