Python – Deleting slices from files with ID

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error Python – Deleting slices from files with ID on this date .

Example: I have a file (1.txt) and the following content:

1 - a
2 - ERROR
3 - b
4 - ERROR
5 - c
6 - ERROR
7 - d
8 - ERROR

and I’d like to create a new_1.txt with:

1 - a
5 - c

As you can see I have the ERROR word as ID, what means: Always that Python finds the word ‘ERROR’, it will look for another ‘ERROR’ word and delete the slice of lines in the file. And so on until the end of the file. So the lines from 2 to 4 will be deleted, and the lines from 6 to 8 as well.

My code is just deleting the lines that contains the word ERROR, but I need to delete the slices.

bad_words = "ERROR"
with open("1.txt") as oldfile, open("new_1.txt", 'w') as newfile:
   for line in oldfile:
       if not any(bad_word in line for bad_word in bad_words):
           newfile.write(line)

I really appreciate your answers!

Answer

Try this:

bad_words = "ERROR"
file_name = "1.txt"
with open(file_name) as oldfile, open('new_'+file_name, 'w') as newfile:
    error_found = False
    for line in oldfile:
        if bad_words in line:
            error_found = error_found ^ True
            continue
        if not error_found:
            newfile.write(line)

Using ^ (xor) operator you will toggle the value of the error_found variable then check it to write or not in the new file.