Home > Net >  How to delete a line before specific word with python
How to delete a line before specific word with python

Time:07-22

so I have text file file.txt e.g

something1
something2
something3
line to be removed
2022-07-21 >>  Ctrl S
something4
something5
something6
something7
line to be removed
2022-07-21 >>  Ctrl S

now how do I make it delete one line before the word Ctrl S in the whole file.

So that the outputfile will be

something1
something2
something3
2022-07-21 >>  Ctrl S
something4
something5
something6
something7
2022-07-21 >>  Ctrl S

Thank you

CodePudding user response:

This should work as desired;

keyword = 'Ctrl S'
new_content = []

with open('textfile.txt', 'r ') as f:
    content = f.readlines()
    prev_index = 0
    for i, line in enumerate(content):
        if keyword in line:
            new_content  = content[prev_index:i - 1]
            prev_index = i
    new_content  = content[prev_index:]
with open('textfile.txt', 'w') as f:
    f.write("".join(new_content))

CodePudding user response:

Try this with a single open statement. Hope it helps you.


with open("textfile.txt", "r ") as f:
    lines = f.readlines()
    f.seek(0)
    for pos, line in enumerate(lines):
        if len(lines)-1 !=pos:
            if "Ctrl S" in lines[pos 1]:
                continue
        f.write(line)
    f.truncate()

CodePudding user response:

You might do smth of the kind:

with open("python_cisco\programs\list.txt", "r") as f:
    lines = f.readlines() # number of bits not to overload your system
    for i in range(len(lines)):
        try:
            if "Ctrl S" in lines[i]:
                lines.remove(lines[i - 1])
        except:
            pass

with open("python_cisco\programs\list2.txt", "w") as f:
    for i in lines:
    f.write(i)

This will basically rewrite the list without unnecessary lines to a different file

  • Related