删除文件中指定的一行

代码原地址:http://stackoverflow.com/questions/2329417/fastest-way-to-delete-a-line-from-large-file-in-python

 完美solution

def removeline(filename, lineno):
    fro = open(filename, "r")        # 文件用于读取

    current_line = 0
    while current_line < lineno:
        fro.readline()
        current_line += 1            # 将文件指针定位到想删除行的开头

    seekpoint = fro.tell()           # 将此时文件指针的位置记录下来
    frw = open(filename, "r+")      # 文件用于写入,与用于读取的文件是同一文件
    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)        # 写入frw
        chars = fro.readline()       # 继续读取,注意此处的读取是按照fro文件的指针来读

    fro.close()
    frw.truncate()                   # 截断,把frw文件指针以后的内容清除
    frw.close()

  

  

posted @ 2016-11-07 16:13  LearnerC  阅读(1631)  评论(0编辑  收藏  举报