删除文件中指定的一行

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

 完美solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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 @   LearnerC  阅读(1641)  评论(0编辑  收藏  举报
编辑推荐:
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
阅读排行:
· dotnet 源代码生成器分析器入门
· 官方的 MCP C# SDK:csharp-sdk
· 一款 .NET 开源、功能强大的远程连接管理工具,支持 RDP、VNC、SSH 等多种主流协议!
· 一步一步教你部署ktransformers,大内存单显卡用上Deepseek-R1
· 一次Java后端服务间歇性响应慢的问题排查记录
点击右上角即可分享
微信分享提示