How to remove lines starting with any prefix using Python?

Last Updated : 22 Jan, 2026

Given a text file, remove all lines that start with a specified prefix. Print the remaining lines and save them into a new file.

Example: (file.txt)

TextGenerator is dummy
Hello World
Python is awesome
TextGenerator skipped

Prefix to remove: "TextGenerator"

Output:
Hello World
Python is awesome

Sample file:

myfile1.txt 

Below are different methods to remove lines starting with a specific prefix:

Using Loop with startswith()

startswith() method checks if a string begins with a specified prefix. It is simple, fast, and memory-efficient.

Python
f1 = open('myfile1.txt','r')
f2 = open('myfile2.txt','w')

for line in f1.readlines():
    if not (line.startswith('TextGenerator')):
      
        print(line, end=' ')
        f2.write(line)

f2.close()
f1.close()

Output

Explanation:

  • line.startswith('TextGenerator'): checks the prefix
  • not: skips lines starting with the prefix
  • print(line, end=''): prints without adding extra newline
  • f2.write(line): writes filtered lines to the new file

Using Loop with find()

find() method returns the index of a substring in a string or -1 if not found. If the prefix is at index 0, we skip that line.

Python
f1 = open('myfile1.txt', 'r')
f2 = open('myfile2.txt', 'w')

for line in f1:
    if line.find('TextGenerator') != 0: 
        print(line, end=' ')
        f2.write(line)

f1.close()
f2.close()

Output:

Explanation:

  • line.find('TextGenerator') == 0: line starts with prefix.
  • != 0: keeps only lines not starting with prefix.

Using Regex (re Module)

Regex allows pattern matching. The ^ metacharacter matches the start of a line. This method is more flexible but slower than startswith().

Python
import re

f1 = open('myfile1.txt', 'r')
f2 = open('myfile2.txt', 'w')

for line in f1:
    if not re.match("^TextGenerator", line):  
        print(line, end=' ')
        f2.write(line)

f1.close()
f2.close()

Output:

Explanation: re.match("^TextGenerator", line) matches prefix at the start of the line

Comment

Explore