过滤大文件将返回一个空的新文件

问题描述 投票:0回答:2

我是python的新手,如果这个问题太基础了,请原谅我。我一直在尝试使用另一个文件(大约100,000行)中的模式来过滤大文件(> 85,000,000行)中的行。我想逐行读取这些文件以节省内存,并将过滤后的行写入另一个文件。大文件包含以下文本:

21:10433614:T:A 21  10433614    T   A   Biallelic_SNP   0.00075642965204236 0   0   0   0   0.000199680511182109
21:10433615:G:T 21  10433615    G   T   Biallelic_SNP   0.00302571860816944 0   0   0   0   0.000798722044728434
21:10433619:T:A 21  10433619    T   A   Biallelic_SNP   0   0   0.00496031746031746 0   0   0.000998402555910543
21:10433640:G:A 21  10433640    G   A   Biallelic_SNP   0   0   0   0   0.00204498977505112 0.000399361022364217
21:10433654:C:T 21  10433654    C   T   Biallelic_SNP   0   0   0   0.00397614314115308 0   0.000798722044728434
rs201609931:10434436:CAT:C  21  10434436    CAT C   Biallelic_INDEL 0.0219364599092284  0   0   0.00198807157057654 0   0.0061900958466453`7

模式是这样的:

21 10433614
21 10433619
21 10433654

输出文件应如下所示:

21:10433614:T:A 21  10433614    T   A   Biallelic_SNP   0.00075642965204236 0   0   0   0   0.000199680511182109
21:10433619:T:A 21  10433619    T   A   Biallelic_SNP   0   0   0.00496031746031746 0   0   0.000998402555910543
21:10433654:C:T 21  10433654    C   T   Biallelic_SNP   0   0   0   0.00397614314115308 0   0.000798722044728434

这里是我正在使用的脚本:

paternFile = open('paterns.txt')
newFile = open('newFile.txt', 'a')
largeFile = open('largeFile.txt')
for line in largeFile:
    string = line
    for row in paternFile:
        patern = row[:-1] #to remove the end of line character
        if re.search(patern, string):
            newFile.write(string)
newFile.close()
largeFile.close()
paternFile.close()

我已经对其进行了部分测试以进行检查,显然它应该可以工作,但是它没有写入我的新文件,因此我不知道为什么。[编辑]感到很惊讶,我检查了条件返回的内容:

print(re.search(patern, string))
NONE

我不明白为什么它不返回TRUE或FALSE。谁能帮忙?

python filtering large-files
2个回答
0
投票

您的问题是文件对象是迭代器。您只能在使用所有条目之前将它们循环一次。您正在针对data.txt文件中的第一行而不是其他任何一个来检查模式。

您可以通过添加]重置模式文件中正在查看的位置>

paternFile.seek(0)

for row in paternFile循环之后

所以更新后的代码如下:

paternFile = open('paterns.txt')
newFile = open('newFile.txt', 'a')
largeFile = open('largeFile.txt')
for line in largeFile:
    string = line
    for row in paternFile:
        patern = row[:-1] #to remove the end of line character
        if re.search(patern, string):
            newFile.write(string)
    paternFile.seek(0)
newFile.close()
largeFile.close()
paternFile.close()

您还可以将所有模式加载到列表等对象中,并根据需要循环多次。但是,鉴于模式文件的绝对大小,此处的迭代器解决方案实际上可能是合适的。


0
投票

根据您的示例。以下实现了预期的输出。

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