import asyncio
import aiocsv
import aiofiles
async def main():
async with aiofiles.open('/tmp/test.csv', mode='w', encoding='utf-8', newline='') as fobj:
writer = aiocsv.AsyncDictWriter(fobj, fieldnames=['foo', 'bar'])
await writer.writeheader()
await writer.writerow({'foo': '1', 'bar': '1'})
await writer.writerow({'foo': '2', 'bar': '2'})
await writer.writerow({'foo': '3', 'bar': '3'})
async with aiofiles.open('/tmp/test.csv', mode='r', encoding='utf-8', newline='') as fobj:
row = aiocsv.AsyncReader(fobj)
print(await anext(row)) # I want to read header only
asyncio.run(main(), debug=True)
Output:
['foo', 'bar']
unhandled exception during asyncio.run() shutdown
task: <Task finished name='Task-2' coro=<<async_generator_athrow without __name__>()> exception=RuntimeError("can't send non-None value to a just-started coroutine") created at /usr/lib/python3.10/asyncio/events.py:80>
RuntimeError: can't send non-None value to a just-started coroutine
Sample code:
Output: