0

How can I delete lines in a text file that contain a specific line?

I'm trying to delete lines where there are no characters> = and <

example

input:

>=3 1 2 3
1 2 3 4
<=2 1 2 3 4

required output:

>=3 1 2 3
<=2 1 2 3 4

I tried it like this but it doesn't work as I imagined

with open("demofile.txt", "r") as f:
    lines = f.readlines()
with open("yourfile.txt", "w") as f:
    for line in lines:
        if line.strip("\n") != "<":
            print(line)
            f.write(line)

1 Answers1

1

Change this if

        if line.strip("\n") != "<":

to

        if any(desired_char in line for desired_char in ("<", ">", "=")):

This way you will keep the lines that contain any of the ("<", ">", "=").

Mustafa Aydın
  • 17,645
  • 4
  • 15
  • 38