在Python中从大文件删除行的最快方法
我正在Linux系统上使用非常大的文本文件(〜11GB)。我正在通过正在检查文件错误的程序来运行它。一旦发现错误,我需要修复该行或完全删除该行。然后重复…
最终,一旦我对流程感到满意,我便将其完全自动化。但是,现在让我们假设我正在手动运行它。
从此大文件中删除特定行最快(就执行时间而言)是什么?我想到了用Python进行此操作…但是可以接受其他示例。该行可能在文件中的 任何位置 。
如果是Python,则采用以下接口:
def removeLine(filename, lineno):
谢谢,
-aj
-
对于同一文件,您可以同时具有两个文件对象(一个用于读取,一个用于写入):
def removeLine(filename, lineno): fro = open(filename, "rb") current_line = 0 while current_line < lineno: fro.readline() current_line += 1 seekpoint = fro.tell() frw = open(filename, "r+b") frw.seek(seekpoint, 0) # read the line we want to discard fro.readline() # now move the rest of the lines in the file # one line back chars = fro.readline() while chars: frw.writelines(chars) chars = fro.readline() fro.close() frw.truncate() frw.close()