用 Python 异步写入 CSV 文件

Sou*_*dra 3 python csv async-await python-asyncio fastapi

我正在编写一个具有以下功能的 CSV 文件:

import csv
import os
import aiofiles


async def write_extract_file(output_filename: str, csv_list: list):
    """
    Write the extracted content into the file
    """
    try:
        async with aiofiles.open(output_filename, "w+") as csv_file:
            writer = csv.DictWriter(csv_file, fieldnames=columns.keys())
            writer.writeheader()
            writer.writerows(csv_list)
    except FileNotFoundError:
        print("Output file not present", output_filename)
        print("Current dir: ", os.getcwd())
        raise FileNotFoundError
Run Code Online (Sandbox Code Playgroud)

但是,由于没有 await 允许 overwriterows方法,因此没有将行写入 CSV 文件。
如何解决这个问题?有没有可用的解决方法?
谢谢你。
整个代码可以在这里找到。

Fom*_*aut 7

您可以使用aiocsv。以下是异步将行写入 CSV 文件的快速示例:

import asyncio
import aiofiles
from aiocsv import AsyncWriter

async def main():
    async with aiofiles.open('your-path.csv', 'w') as f:
        writer = AsyncWriter(f)
        await writer.writerow(['name', 'age'])
        await writer.writerow(['John', 25])

asyncio.run(main())
Run Code Online (Sandbox Code Playgroud)

更多示例如下: https: //pypi.org/project/aiocsv/


ale*_*ame 5

在我看来,最好不要尝试将aiofilescsv模块一起使用并运行同步代码 usingloop.run_in_executor并异步等待它,如下所示:

def write_extract_file(output_filename: str, csv_list: list):
    """
    Write the extracted content into the file
    """
    try:
        with open(output_filename, "w+") as csv_file:
            writer = csv.DictWriter(csv_file, fieldnames=columns.keys())
            writer.writeheader()
            writer.writerows(csv_list)
    except FileNotFoundError:
        print("Output file not present", output_filename)
        print("Current dir: ", os.getcwd())
        raise FileNotFoundError


async def main():
    loop = asyncio.get_running_loop()
    await loop.run_in_executor(None, write_extract_file, 'test.csv', csv_list)
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这会同步运行“write_extract_file”。您需要使用“await loop.run_in_executor(None, write_extract_file, 'test.csv', csv_list)”来实际异步运行它 (2认同)