python同时逐行分析两个大文件

时间:2014-05-14 12:43:13

标签: python

我正在尝试分析两个±6 GB的文件。我需要同时分析它们,因为我需要同时使用两行(每个文件一行)。我试着做这样的事情:

with open(fileOne, "r") as First_file:
    for index, line in enumerate(First_file):

        # Do some stuff here

    with open(fileTwo, "r") as Second_file:
        for index, line in enumerate(Second_file):

            # Do stuff here aswell

问题是在第二个“with open”循环开始于文件的开头。因此,分析将花费很长时间。我也试过这个:

with open(fileOne, "r") as f1, open(fileTwo, "r") as f2:
    for index, (line_R1, line_R2) in enumerate(zip(f1, f2)):

问题是两个文件都直接加载到内存中。我需要每个文件中的相同行。正确的行是:

number_line%4 == 1

这将给出第2,5,9,13行等。我需要两个文件中的那些行。

有更快的方法和更高效的内存方式吗?

1 个答案:

答案 0 :(得分:7)

在Python 2中,使用itertools.izip()来防止文件被加载到内存中:

from itertools import izip

with open(fileOne, "r") as f1, open(fileTwo, "r") as f2:
    for index, (line_R1, line_R2) in enumerate(izip(f1, f2)):

内置的zip()函数确实会将两个文件对象全部读入内存,izip()一次检索一行。

相关问题