3

Simple as the title, really. But struggling somehow.

delete lines with 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()

I'm not understanding the best way to delete or clear the line completely.

wetin
  • 360
  • 1
  • 3
  • 13

2 Answers2

4

You can open your file in read-write mode and delete the lines that match a condition.

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()

The seek resets the file pointer.

Reference: using Python for deleting a specific line in a file

bumblebee
  • 1,811
  • 12
  • 19
1

Open the file and read its contents, then open the file again write the line to it but without the lines containing '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)
jared_mamrot
  • 22,354
  • 4
  • 21
  • 46