Feb-18-2023, 02:49 PM
Filter lines as they are read. Close the file and reopen as write. Write the lines.
import re pattern = re.compile(r'\d\d:\d\d') with open('test.txt', 'r') as file: lines = [line for line in file if not re.match(pattern, line)] with open('test.txt', 'w') as file: file.writelines(lines)You could also open the file using 'r+' mode, skipping having to close and re-open the file, but why?
import re pattern = re.compile(r'\d\d:\d\d') with open('test.txt', 'r+') as file: lines = [line for line in file if not re.match(pattern, line)] file.truncate(0) file.seek(0) file.writelines(lines)