|Artificial Intelligence Tutorial|
|Machine Learning Projects Tutorial||Python Video tutorial|
|Computer Graphics Video Tutorial||C++ Video Tutorial|
|Big Data Analytics Video Tutorial||Soft Computing Video Tutorial|
|Placement Video Tutorial||Java Video Tutorial|
Python program to extract all lines those start with From
Develop a simple python program to read a file name and extract all lines those start with “From” in a given file.
Step by Step solution to Problem
First, read the filename from the user and store it in variable fname.
Open the file with an “open” function in reading mode. If the file is not opened then the display file is not found (this can be handled by try and except blocks), otherwise continue with execution.
Read the contents of the file line by line using for loop. In every iteration, one line will be read.
Remove the leading and trailing extract characters using the strip() function.
There are two possible solutions to check the line starts with “From”. Check whether the line starts with “From” using starts with function or use regular expression and search() function check the line starts with “From”.
If the line starts with “From” display the line using the print() function.
Program Source code using startswith() function
fname = input("Enter the file name: ") try: fhand = open(fname) for line in fhand: line = line.rstrip() if (line.startswith('From')): print (line) except: print("File not found")
Program Source code using regular expression and search() function
import re fname = input("Enter the file name: ") try: fhand = open(fname) for line in fhand: line = line.rstrip() if (re.search('^From', line)): print (line) except: print("File not found")
Consider input text file for demonstration say, test.txt with following contents
Name: Mahesh Huddar
Output of Program
Enter the file name: test.txt
This tutorial discusses how to write a simple python program to read a file name and extract lines those start with “From” in a given file.