Search code examples
pythonpython-3.xfilelinefile-handling

How to delete a line before specific word with python


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


Solution

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