【问题标题】:Asyncio file reading jsonAsyncio file reading json
【发布时间】: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:

  1. import aiofiles
  2. read the file
  3. 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 asyncio module alone, so was wondering if this is achievable in that module or if it is necessary to use aiofiles or if i have missed a better method altogether ?

【问题讨论】:

    标签: python json python-asyncio


    【解决方案1】:

    asyncio does not support asynchronous file operations, you can see the asyncio wiki for further explanation

    aiofiles allows you to read files asynchronously by delegating their operations to a separate thread pool

    【讨论】:

      猜你喜欢
      • 2017-06-29
      • 1970-01-01
      • 1970-01-01
      • 2021-11-03
      • 2019-12-11
      • 2015-11-13
      • 2016-01-24
      • 2022-12-27
      • 2020-03-12
      相关资源
      最近更新 更多