How to remove lines starting with any prefix using Python?
Given a text file, read the content of that text file line by line and print only those lines which do not start with defined prefix. Also store those printed lines in another text file. There are following ways in which this task can be done:
Method 1: Using loop and startswith().
In this method, we read the contents of file line by line. While reading, we check if the line begins with the given prefix, we simply skip that line and print it. Also store that line in another text file.
Suppose the text file from which lines should be read is given below:
It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
It was popularised in the 1960s with the release of Letraset sheets containing TextGenerator passages, and more recently with desktop publishing software like Albus Potter including versions of TextGenerator.
In the above example, we open a file and read its content line by line. We check if that line begins with given prefix using startswith() method. If that line begins with “TextGenerator” we skip that line, else we print the line and store it in another file. In this way, we could remove lines starting with specified prefix.
Method 2: Using Regex.
In this method we use re module of python which offers a set of metacharacters. Metacharacters are characters with special meaning. To remove lines starting with specified prefix, we use “^” (Starts with) metacharacter.
We also make use of re.findall() function which returns a list containing all matches.
In the above example, we open a file and read its content line by line. We check if that line begins with “Geeks” using regular exapression. If that line begins with “Geeks” we skip that line, and we print the rest of the lines and store those lines in another file.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course