Прочтите строки файла и запишите их обратно, за исключением строк от кнопки запуска до кнопки остановки, вот пример:
def erase(file_name: str, start_key: str, stop_key: str):
"""
This function will delete all line from the givin start_key
until the stop_key. (include: start_key) (exclude: stop_key)
"""
try:
# read the file lines
with open(file_name, 'r+') as fr:
lines = fr.readlines()
# write the file lines except the start_key until the stop_key
with open(file_name, 'w+') as fw:
# delete variable to control deletion
delete = False
# iterate over the file lines
for line in lines:
# check if the line is a start_key
# set delete to True (start deleting)
if line.strip('\n') == start_key:
delete = True
# check if the line is a stop_key
# set delete to False (stop deleting)
elif line.strip('\n') == stop_key:
delete = False
# write the line back based on delete value
# if the delete setten to True this will
# not be executed (the line will be skipped)
if not delete:
fw.write(line)
except RuntimeError as ex:
print(f"erase error:\n\t{ex}")
Использование:
erase('file.txt', 'Key-Word', 'Key-Word2')
file.txt (ввод):
Line1
Line2
Line3
Key-Word
Line4
Line5
Key-Word2
Line6
Line7
после запуска функции:
Line1
Line2
Line3
Key-Word2
Line6
Line7