Skip to main content
 首页 » 编程设计

python之在 Python 中处理大文本文件

2025年05月04日13txw1958

基础知识是我需要逐行处理 4gig 文本文件。

使用 .readline() 或 for line in f 非常适合内存,但需要很长时间才能完成 IO。想使用 yield 之类的东西,但(我认为)会切断线路。

可能的答案:

file.readlines([sizehint])¶ 
Read until EOF using readline() and return a list containing the lines 

thus read. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read. Objects implementing a file-like interface may choose to ignore sizehint if it cannot be implemented, or cannot be implemented efficiently.

没想到你可以做到这一点!

请您参考如下方法:

您可以只遍历文件对象:

with open("filename") as f: 
    for line in f: 
        whatever 

这将进行一些内部缓冲以提高性能。 (请注意,file.readline() 的性能会差很多,因为它没有缓冲——这就是为什么您不能将对文件对象的迭代与 file.readline().)