Home > Blockchain >  How to delete one line before a specific word in a text file in python
How to delete one line before a specific word in a text file in python

Time:07-20

so I have text file file.txt e.g

something1
something2
something3
line to be removed
Ctrl S
something4
something5
something6
something7
line to be removed
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
Ctrl S
something4
something5
something6
something7
Ctrl S

Thank you

CodePudding user response:

Maybe this will help you:

import re

with open('file.txt') as f:
    text = f.read()

text = re.sub(r'(Ctrl\ S)(\n[^\n] )(?=\nCtrl\ S)', '\\1\\3', text)

with open('file.txt', 'w') as f:
    f.write(text)

CodePudding user response:

f = open("file.txt",'r')
lines = f.readlines()
f.close()

excludedWord = "whatever you want to get rid of"

newLines = []
for line in lines:
    newLines.append(' '.join([word for word in line.split() if word != 
    excludedWord]))

f = open("file.txt", 'w')
for line in lines:
f.write("{}\n".format(line))
f.close()

This might be of some use!

CodePudding user response:

# open two files: one for reading, one for writing
with open('file.txt', 'rt') as in_, open('out.txt', 'wt') as out:
    # if we're considering two lines, we have to store the other one
    old_line = None
    for line in in_:  # iterating over a text file gives lines
        if old_line is not None and line != "Ctrl S\n":
            # we can write the previous line each iteration
            out.write(old_line)
        old_line = line
    if old_line is not None:
        # but we have to make sure to write the last one,
        # since it's never the previous line
        out.write(old_line)

This approach doesn't store the whole file in memory, so it works for larger files – so long as a line isn't too long, that is!

  • Related