![](/img/trans.png)
[英]How to read data corresponds to specific line numbers from a 60GB text file in python?
[英]How to remove all lines from a large text file (>60GB) that contains a specific alphabet in python?
我有一个大文本文件 (>60GB),我想从中删除某些行。
文本文件包含:
352_0M, 352_1M, 0.913
500_1F, 452_0M, 0.500
870_0M, 400_1F, 0.980
601_1F, 470_0M, 0.630
845_0M, 900_1M, 0.456
100_1F, 250_0F, 0.123
...
我想删除第一列或第二列或两者中包含“F”字母的所有行。 预期的输出是:
352_0M, 352_1M, 0.913
845_0M, 900_1M, 0.456
如何在python中做到这一点?
with open('input_file','r') as inf:
with open('output_file','w') as outf:
for line in inf:
if not any('F' in x for x in line.split(',', 2)[:2]):
outf.write(line)
numpy 的解决方案
import numpy as np
A = np.loadtxt('input_file',dtype=str,delimiter=', ')
id1 = [ 'F' not in a for a in A.T[0]]
id2 = [ 'F' not in a for a in A.T[1]]
B = A[np.bitwise_and(id1,id2)]
np.savetxt('file_out',B)
编辑:感谢 Marcos 和 AMC 的评论。 虽然我提出的解决方案要快一点,但我纠正了自己:不是! Błotosmętek 的解决方案在性能和 RAM 使用方面都要好得多。 我检查了一个 600 GB 的测试文件,建议的 numpy 解决方案比 Błotosmętek 的解决方案差两倍。
尝试用python将文件拆分成多个部分,然后搜索特定的单词。 处理大文件非常困难,因为它需要巨大的 RAM 容量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.