删除文件中的一行

在不新建文件的情况下,删除文件filename中第lineno行。
这里使用两个open

  • 简洁版
    读取除lineno的其它行
def removeLine(filename, lineno):
    fro = open(filename, "rt")
    frw = open(filename, "r+t")
    for i, d in enumerate(fro):
        if i != lineno:	 # 读取除lineno的其它行
            frw.write(d)
    frw.truncate()
    fro.close()
    frw.close()

truncate()表示对文件进行截断
frw.write()从frw文件的首端开始写

  • 高效版
    该方法只对删除行之后的行进行写入操作;
    frofra是一个生成器,使用fro.tell()frw.seek(seekpoint, 0)找到行偏移量以及指向特定的偏移量。
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()

参考:
如何在一个文件中删除一行

猜你喜欢

转载自blog.csdn.net/Hollybobo79/article/details/84074427