Program to remove lines starting with any prefix using Python

by | Aug 2, 2021 | Python Programs

Home » Python » Python Programs » Program to remove lines starting with any prefix using Python

Introduction

The task is to print the lines of text that are not starting with given prefix.

Program

Approach 1

Program to remove lines starting with any prefix using Python

#Open file in read mode

openFile = open('demo.txt', 'r') 

#Open file in write mode

writeFile = open('updatedFile.txt', 'w') 

#Read lines 

for txtLine in openFile .readlines(): 

    if not (txtLine.startswith('Python')): 

        print(txtLine)  

#Write lines to file

        writeFile.write(txtLine) 

writeFile.close() 

openFile.close()

Output:

Program to remove lines starting with any prefix using Python Output

Approach 2

Program to remove lines starting with any prefix using Python 2

import re 

#Open file in read mode

openFile = open('demo.txt','r')

#Open file in write mode 

writeFile = open('updatedFile.txt','w')  

for txtLine in openFile.readlines():

#Search pattern 

    search = re.findall("^Python", txtLine)      

    if not search: 

        print(txtLine) 

        writeFile.write(txtLine) 

openFile.close() 

writeFile.close()

Output:

Program to remove lines starting with any prefix using Python Output 2

Explanation

Approach 1:

  • Open and read the lines of the text file.
  • We have used startswith() function to check whether the line is starting with word Python. If the line does not start with word Python, the line is printed on screen and stored to another text file. If the line starts with word Python, the next statement is skipped and we will check the next line.

Approach 2:

  • Open and read the lines of the text file.
  • We have used regular expression to check for the line starting with Python. If the specified pattern (^Python) is not found, the line is printed on the screen and stored in another file.

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author