python 非阻塞写入csv文件
python non blocking write csv file
我正在编写一些 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 中阅读了一些关于异步的文章,但我不知道如何实现它。有没有一种简单的方法可以优化这个循环,让它不等到写入完成就开始下一次迭代?
由于大多数操作系统 don't support 异步文件 I/O,现在常见的跨平台方法是使用线程。
例如aiofiles模块包装线程池为asyncio提供文件I/OAPI。
由于 numpy 和 pandas io 都不是 asyncio 感知的,因此这对于线程来说可能比 asyncio 更好。 (此外,基于 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 代码来进行一些计算并将结果写入文件。这是我当前的代码:
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 中阅读了一些关于异步的文章,但我不知道如何实现它。有没有一种简单的方法可以优化这个循环,让它不等到写入完成就开始下一次迭代?
由于大多数操作系统 don't support 异步文件 I/O,现在常见的跨平台方法是使用线程。
例如aiofiles模块包装线程池为asyncio提供文件I/OAPI。
由于 numpy 和 pandas io 都不是 asyncio 感知的,因此这对于线程来说可能比 asyncio 更好。 (此外,基于 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.
此外,请考虑为每次写入重新打开文件会减慢写入速度。如果写入的数据量较小,也许你可以通过预先打开文件来获得更好的性能。