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: 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
for line in freads the file one line at a time.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.- 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. countgoes 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
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.
Related programs
- Count Words in a Text File
- Copy Lines Without the Letter 'a' to Another File
- Count the Words "Me" and "My" in a Text File
- Read a Text File and Separate Words with #
- Count Vowels, Consonants, Uppercase and Lowercase Characters in a Text File
- Search a Roll Number in a Binary File
- Update Marks in a Binary File
- Store and Search User IDs and Passwords in a CSV File
- Read a File Line by Line
All Python programs · CBSE class 12 practical file · Python exercises