zoukankan      html  css  js  c++  java
  • 删除文件中指定的一行

    代码原地址: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()
    

      

      

  • 相关阅读:
    npm 一些常用的命令
    Angular Encapsulation
    隐藏scrollbar
    Vue生命周期详解(1)- 单个组件
    如何自己制作iconfont
    day07-2018-10--25 深浅拷贝
    day06-2018-10--24 小数据池和编码
    day05-2018-10--23 字典
    day04-2018-10--22python基础
    day03-2018-10-19-python基础
  • 原文地址:https://www.cnblogs.com/learnC/p/6039338.html
Copyright © 2011-2022 走看看