簡體   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