删除文件中的一行

在不新建文件的情况下,删除文件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()

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值