Python program to extract all lines those start with From

 

Python program to extract all lines those start with From

Problem Definition

Develop a simple python program to read a file name and extract all lines those start with “From” in a given file.

Video Tutorial

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
From: Karanataka

From: xyz@abc.com
To: pqr@abc.com

X-DSPAM-Confidence:999.8475
X-DSPAM-Probability:0.0000

Mail From: XYZ123@ABC.COM
To: PQR123@ABC.COM

X-DSPAM-Confidence:91.9125
X-DSPAM-Probability:11.0080

Output of Program

Enter the file name: test.txt

From: Karanataka

From: xyz@abc.com

Summary:

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.

Leave a Comment

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