python非阻塞写入csv文件

标签 python python-multithreading python-asyncio

我正在编写一些 python 代码来进行一些计算并将结果写入文件。这是我当前的代码:

for name, group in data.groupby('Date'):
    df = lot_of_numpy_calculations(group)

    with open('result.csv', 'a') as f:
        df.to_csv(f, header=False, index=False)

有时计算和写入都需要。我读了一些关于 python 中异步的文章,但我不知道如何实现它。有没有一种简单的方法可以优化这个循环,使其不等到写入完成才开始下一次迭代?

最佳答案

由于 numpy 和 pandas io 都不支持异步,因此与异步相比,这可能是线程更好的用例。 (此外,基于 asyncio 的解决方案无论如何都会在幕后使用线程。)

例如,此代码生成一个编写器线程,您可以使用队列向其提交工作:

import threading, queue

to_write = queue.Queue()

def writer():
    # Call to_write.get() until it returns None
    for df in iter(to_write.get, None):
        with open('result.csv', 'a') as f:
            df.to_csv(f, header=False, index=False)
threading.Thread(target=writer).start()

for name, group in data.groupby('Date'):
    df = lot_of_numpy_calculations(group)
    to_write.put(df)
# enqueue None to instruct the writer thread to exit
to_write.put(None)

请注意,如果写入始终比计算慢,队列将不断累积数据帧,最终可能会消耗大量内存。在这种情况下,请务必通过将 maxsize 参数传递给 constructor 来为队列提供最大大小。 .

此外,考虑到为每次写入重新打开文件会减慢写入速度。如果写入的数据量较小,也许您可​​以通过预先打开文件来获得更好的性能。

关于python非阻塞写入csv文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50066619/

相关文章:

data-visualization - 在自组织 map 绘图或鸢尾花数据集中可视化类标签

python - 使用过滤器和排除来过滤对象及其实例

仅适用于开发环境的 Python 应用程序多线程

python - 如何使两个函数仅在其中一个函数完成其工作后才相互跟随

python - aiohttp:设置每秒最大请求数

python-asyncio - pynng:如何在 REP0 套接字上设置并继续使用多个上下文

python - 从python中的行中提取特定数据

android - 使用 PyCrypto 验证来自 Google Licensing 的 RSA 签名

python - "File format is not supported"同时多线程处理 pdf 文件列表

python - 如何在Python3中将异步生成器流转换为类似文件的对象?