Editor

Python Program to Display Lines Starting with T in a Text File

Beginner · File handling · CBSE class 12 practical list

This program reads a text file, displays only the lines that begin with a capital T, and then prints how many such lines there were. It is a common CBSE class 12 practical and board exam question on text files.

Program

lines_starting_with_t.py
# Make a sample file to work on (in your practical file, this file already exists)
with open("notes.txt", "w") as f:
f.write("The sun rises in the east.\n")
f.write("Birds start singing early.\n")
f.write("Trees sway in the morning breeze.\n")
f.write("the dew is still on the grass.\n")
f.write("Today is a good day to read.\n")
count = 0
print("Lines starting with T:")
with open("notes.txt", "r") as f:
for line in f:
if line.startswith("T"):
print(line, end="") # the line already ends with a new line
count += 1
print("Number of lines starting with T:", count)
Output
Lines starting with T:
The sun rises in the east.
Trees sway in the morning breeze.
Today is a good day to read.
Number of lines starting with T: 3

How it works

  1. for line in f reads the file one line at a time.
  2. line.startswith("T") is True when the very first character is a capital T, so the line that begins with a small "the" is skipped.
  3. Each line read from a file still has its newline at the end, so print(line, end="") avoids an extra blank line after every line.
  4. count goes up by one for every matching line, and the total is printed at the end.

Another way to write it

Using readlines() in a function

Using readlines() in a function
# Make a sample file to work on (in your practical file, this file already exists)
with open("notes.txt", "w") as f:
f.write("The sun rises in the east.\nBirds start singing early.\nTrees sway in the breeze.\n")
def show_t_lines(filename):
with open(filename, "r") as f:
lines = f.readlines() # a list with one string per line
count = 0
for line in lines:
if line[0] == "T":
print(line.strip())
count += 1
return count
print("Lines starting with T:", show_t_lines("notes.txt"))
Output
The sun rises in the east.
Trees sway in the breeze.
Lines starting with T: 2

readlines() loads all the lines into a list first, and line.strip() removes the newline so a plain print() can be used. Exam questions often ask for the count to be returned from a function like this.

Try it yourself

Change the condition to line.lower().startswith("t") so that the line starting with a small t is shown too.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises