Table of Contents
Introduction
The task is to print the lines of text that are not starting with given prefix.
Program
Approach 1
#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:
Approach 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:
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.
0 Comments