代码之家  ›  专栏  ›  技术社区  ›  wetin

从文本文件中删除或清除行

  •  0
  • wetin  · 技术社区  · 6 年前

    删除带有boop的行

    beep
    boop 
    bop 
    Hey 
    beep
    boop
    bop
    
    file_path = "C:\\downloads\\test.txt"
    with open(file_path, "r") as f:
        lines = f.readlines()
    with open(file_path, "w") as f:
        for line in lines:
            if line.rfind("boop") >= 0:
                f.write(line)
    
    file_in.close()
    

    2 回复  |  直到 6 年前
        1
  •  3
  •   bumblebee    6 年前

    您可以以读写模式打开文件并删除符合条件的行。

    with open(file_path, "r+") as fp:
        lines = fp.readlines()
        fp.seek(0)
        for line in lines:
            if "boop" not in line:
                fp.write(line)
        fp.truncate()
    

    这个 seek

    参考: using Python for deleting a specific line in a file

        2
  •  1
  •   jared_mamrot    6 年前

    path='path/to/file.txt'
    with open(path, "r") as f:
        lines = f.readlines()
        with open(path, "w") as f:
            for line in lines:
                if line.strip("\n") != "boop":
                    f.write(line)