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

时间:2020-05-13 04:03:54

标签: python python-3.x

真的很简单。但是以某种方式挣扎。

用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 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:1)

打开文件并读取其内容,然后再次打开文件,向其中写入一行,但不包含“ boop”行:

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)