【发布时间】:2022-12-02 01:18:54
【问题描述】:
I am trying to read a json file in anasync function.
I managed to find this code that works, but is rather clunky in the sense that it requires three extra parts for the file read:
- import
aiofiles - read the file
- convert file to dict
import aiofiles import asyncio import json async def main(): # Read the contents of the json file. async with aiofiles.open('rhydon.json', mode='r') as f: contents = await f.read() # Load it into a dictionary and create a list of moves. pokemon = json.loads(contents) name = pokemon['name'] moves = [move['move']['name'] for move in pokemon['moves']] # Open a new file to write the list of moves into. async with aiofiles.open(f'{name}_moves.txt', mode='w') as f: await f.write('\n'.join(moves)) asyncio.run(main())Ideally, i would like to use just the
asynciomodule alone, so was wondering if this is achievable in that module or if it is necessary to useaiofilesor if i have missed a better method altogether ?
【问题讨论】:
标签: python json python-asyncio