繁体   English   中英

Python三重奏,在循环内保存JSON

[英]Python trio, Saving JSON under loop within

目前,我正在接收来自接收方频道的rec function 中的命令。

async def rec(receiver):
    with open('data.json', 'w', encoding='utf-8', buffering=1) as f:
        f.write('[\n')
        async with receiver:
            count = 0
            async for val in receiver:
                count += 1
                if count != 1:
                    f.write(',')
                json.dump(val, f, indent=4, ensure_ascii=False)
        print(f'[*] - Active items: {count}')
        f.write('\n]')

我不确定这是否算作将 JSON 转储到 for 循环下的文件中的正确方法。 请告知是否有更多 Pythonic 方式。

好吧,使这段代码更符合 Python 标准的一项改进是重新排序if count …测试如下:

    async with receiver:
        count = 0
        async for val in receiver:
            if count:
                f.write(',')
            count += 1
            json.dump(val, f, indent=4, ensure_ascii=False)

此外,您可能希望将文件名作为参数传递,并在逗号后添加一个换行符。

因为那里没有重要的 JSON 流媒体模块 AFAIK,我会以基本相同的方式编写这段代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM