【问题标题】:Stream to JSON file using yield使用 yield 流式传输到 JSON 文件
【发布时间】:2015-01-27 19:52:37
【问题描述】:

我有一个函数可以读取一个读取块的文件,并在每次迭代后返回以下内容。

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

之前,我将所有这些返回的字典存储到一个字典中,然后他们将整个字典转储到一个 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() 从文件中读取每个字典时一一转储。我该怎么做?

【问题讨论】:

    标签: python json dictionary


    【解决方案1】:
    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)
    

    【讨论】:

    • 感谢您的回复,但是当我运行该脚本TypeError: <open file 'my_out.json', mode 'ab' at 0x0000000002B3FB70> is not JSON serializable 时出现此错误,尽管print item 正确输出了字典!
    • 哎呀,论点倒退了……现在修复了
    猜你喜欢
    • 1970-01-01
    • 2021-11-08
    • 2016-08-09
    • 1970-01-01
    • 2012-06-18
    • 2013-05-04
    • 2018-08-01
    • 2019-01-10
    • 2019-07-25
    相关资源
    最近更新 更多