Fastest Way to Delete a Line from Large File in Python

前端 未结 9 661
轮回少年
轮回少年 2020-11-30 03:58

I am working with a very large (~11GB) text file on a Linux system. I am running it through a program which is checking the file for errors. Once an error is found, I need

9条回答
  •  伪装坚强ぢ
    2020-11-30 04:49

    You can have two file objects for the same file at the same time (one for reading, one for writing):

    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()
    

提交回复
热议问题