How to remove lines starting with any prefix using Python?

Published on Aug. 22, 2023, 12:15 p.m.

To remove lines starting with any prefix in Python, you can use regular expressions or simple string operations. Here is an example using regular expressions and the re module:

import re

prefix = "prefix" # the prefix you want to remove

with open('file.txt', 'r') as f:
    filtered_lines = [line for line in f if not re.match('^'+prefix, line)]

with open('new_file.txt', 'w') as f:
    f.writelines(filtered_lines)

This reads lines from a file, removes lines that start with the specified prefix using regular expression and writes the remaining lines to a new file. Alternatively, you can use the string method startswith() to check if the line starts with the specified prefix and skip it if it does. Here is an example:

prefix = "prefix" # the prefix you want to remove

with open('file.txt', 'r') as f:
    filtered_lines = [line for line in f if not line.startswith(prefix)]

with open('new_file.txt', 'w') as f:
    f.writelines(filtered_lines)

This code reads lines from a file, removes lines that start with the specified prefix using the startswith() method and writes the remaining lines to a new file.

Tags:

related content