Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📁 Unit 1 – File Handling  ·  Lesson 06

Text File Programs (Board Pattern)

Sample file

Board papers usually ask: "Write a function in Python to read the file XYZ.TXT and …". Every program on this page works on the same file story.txt. Run the first program once to create it.

Python
# Create the sample file used by all programs below
text = """The sun rises in the east.
Early birds catch the worm.
My school is near the river.
A good book is a best friend.
Time and tide wait for none.
"""
with open('story.txt', 'w') as f:
    f.write(text)
print('story.txt created with', text.count('\n'), 'lines')
story.txt created with 5 lines
story.txt
The sun rises in the east.
Early birds catch the worm.
My school is near the river.
A good book is a best friend.
Time and tide wait for none.

Counting characters, words, lines

Python
# 1. Count characters, words and lines
def count_all():
    with open('story.txt') as f:
        data = f.read()
    print('Characters:', len(data))
    print('Words     :', len(data.split()))
    print('Lines     :', len(data.splitlines()))
count_all()
Characters: 143 Words : 30 Lines : 5

Counting a specific word

Python
# 2. Count the word "the" (any case, ignoring punctuation)
def count_the():
    count = 0
    with open('story.txt') as f:
        for word in f.read().split():
            if word.strip('.,!?').lower() == 'the':
                count += 1
    print('"the" occurs', count, 'times')
count_the()
"the" occurs 4 times

Lines starting with a letter

Python
# 3. Display lines starting with 'T' and count them
def lines_with_T():
    n = 0
    with open('story.txt') as f:
        for line in f:
            if line[0] == 'T':
                print(line, end='')
                n += 1
    print('Total:', n)
lines_with_T()
The sun rises in the east. Time and tide wait for none. Total: 2

Vowels, consonants, cases

Python
# 4. Count vowels, consonants, uppercase and lowercase letters
def letters():
    v = c = up = low = 0
    with open('story.txt') as f:
        for ch in f.read():
            if ch.isalpha():
                if ch.lower() in 'aeiou':
                    v += 1
                else:
                    c += 1
                if ch.isupper():
                    up += 1
                else:
                    low += 1
    print('Vowels:', v, 'Consonants:', c, 'Upper:', up, 'Lower:', low)
letters()
Vowels: 42 Consonants: 66 Upper: 5 Lower: 103

Short words and Me/My

Python
# 5. Display words with fewer than 4 characters
def short_words():
    with open('story.txt') as f:
        words = [w.strip('.,') for w in f.read().split()]
    print([w for w in words if len(w) < 4])
short_words()
['The', 'sun', 'in', 'the', 'the', 'My', 'is', 'the', 'A', 'is', 'a', 'and', 'for']
Python
# 6. Count "Me" and "My" words (classic board question)
def me_my():
    count = 0
    with open('story.txt') as f:
        for w in f.read().split():
            if w.strip('.,') in ('Me', 'My', 'me', 'my'):
                count += 1
    print('Count of Me/My:', count)
me_my()
Count of Me/My: 1

Copying selected lines

Python
# 7. Copy lines NOT starting with a vowel into another file
def copy_lines():
    with open('story.txt') as src, open('result.txt', 'w') as dst:
        for line in src:
            if line[0].lower() not in 'aeiou':
                dst.write(line)
    with open('result.txt') as f:
        print(f.read(), end='')
copy_lines()
The sun rises in the east. My school is near the river. Time and tide wait for none.

Longest line and numbering

Python
# 8. Longest line and line numbers
def longest():
    with open('story.txt') as f:
        lines = f.readlines()
    for i, line in enumerate(lines, 1):
        print(i, len(line.strip()), line.strip())
    big = max(lines, key=len)
    print('Longest:', big.strip())
longest()
1 26 The sun rises in the east. 2 27 Early birds catch the worm. 3 28 My school is near the river. 4 29 A good book is a best friend. 5 28 Time and tide wait for none. Longest: A good book is a best friend.

Replacing and reversing

Python
# 9. Replace a word and save the file
def replace_word(old, new):
    with open('story.txt') as f:
        data = f.read()
    with open('story_new.txt', 'w') as f:
        f.write(data.replace(old, new))
    with open('story_new.txt') as f:
        print(f.readline(), end='')
replace_word('sun', 'moon')
The moon rises in the east.
Python
# 10. Display each line in reverse and words in reverse order
with open('story.txt') as f:
    for line in f.readlines()[:2]:
        line = line.strip()
        print(line[::-1], '|', ' '.join(line.split()[::-1]))
.tsae eht ni sesir nus ehT | east. the in rises sun The .mrow eht hctac sdrib ylraE | worm. the catch birds Early

Word frequency and blank lines

Python
# 11. Count frequency of each word
freq = {}
with open('story.txt') as f:
    for w in f.read().lower().split():
        w = w.strip('.,')
        freq[w] = freq.get(w, 0) + 1
top = sorted(freq.items(), key=lambda kv: (-kv[1], kv[0]))[:3]
print(top)
[('the', 4), ('a', 2), ('is', 2)]
Python
# 12. Count lines ending with a full stop and remove blank lines
with open('mixed.txt', 'w') as f:
    f.write('Hello.\n\nPython is fun\n\nBye.\n')
with open('mixed.txt') as f:
    lines = [l for l in f if l.strip()]
print('Non-blank lines:', len(lines))
print('Ending with "." :', sum(1 for l in lines if l.rstrip().endswith('.')))
Non-blank lines: 3 Ending with "." : 2

Board-answer tips

  1. 1Write the function header exactly as asked, e.g. def COUNTLINES():.
  2. 2Open the file with the given name and mode 'r'; prefer with or remember close().
  3. 3Choose the right reading method: read() for characters/words, readlines() or a for-loop for lines.
  4. 4Remove punctuation/newline with strip() before comparing.
  5. 5Print or return the final count as asked.
Steps that earn full marks

Frequently Asked Questions

How do I count words in a text file?
Read the file with read(), split it with split() (which splits on any whitespace) and take len() of the resulting list.
Why use strip() while comparing words?
Words in a file often carry punctuation or a newline, like "east." or "worm.\n". strip(".,") or strip() removes them so comparisons work.
← Class 12 Computer Science
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicBinary Files with pickle Your progress: 6 / 26 (23%) · Lesson 7 / 26 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free