逐行读取大文件-内存管理和性能-Python [关闭]

问题描述 投票:0回答:1
我正在尝试在Python中逐行读取大型文本文件(> 5GB)的最佳方法,同时兼顾性能和内存。每行也将被顺序处理(例如,将字符串切成薄片并将其推入某个函数)。

某些解决方案可能在Python中使用并行线程/多线程以使其运行更快??

非常感谢您的帮助或朝正确的方向前进。

python multithreading performance memory large-files
1个回答
0
投票
[在问题Fastest implementation for reading in large pandas Dataframes in parallel?中说过,在每行中完成的处理都应该花费一些费用。否则,您将一无所获。这里有一个有关如何读取csv文件以生成另一个csv文件的示例。我的4个CPU的笔记本电脑的速度几乎完美。对我来说,treat_chunk是一项强大的功能,只需更改您想要的内容即可。在此示例中,您可以在需要时传递其他参数。在https://docs.python.org/3/library/multiprocessing.html中查找有关apply_async的更多信息。另外,该函数的返回结果是一个Pandas数据框(这就是为什么我可以直接到.to_csv()的原因。

def treat_chunk(chunk, a, b, **kwargs): return chunk chunk_size=10 with open("input.csv") as input_stream: for chunk in iter(lambda: list(islice(input_stream, chunk_size)), []): results.append(mp_pool.apply_async(treat_chunk, (chunk, other_param_a, other_param_b), field_dictionary)) with open("output.csv") as output_stream: for i in range(0, len(results)): current_chunk = results[i].get() s = io.StringIO() current_chunk.to_csv(s, sep='\t', na_rep='.', index=False, header=False) output_stream.write(s.getvalue())

此外,我使用流,因此可以使用标准的输入和输出来重定向而不是使用文件。

无论如何,如果要进行的计算真的很轻,您将不会有太大的改进,因为您仍然会受到I / O的限制。

© www.soinside.com 2019 - 2024. All rights reserved.