Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
📁 Unit 1 – File Handling  ·  Lesson 06

Text File Programs (Board Pattern)

Sample file

Board papers में आमतौर पर पूछा जाता है: "Write a function in Python to read the file XYZ.TXT and …"। इस page का हर program एक ही file story.txt पर काम करता है। उसे बनाने के लिए पहला program एक बार चलाएँ।

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.

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

ख़ास 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

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

छोटे words और 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

चुनी हुई lines copy करना

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.

सबसे लंबी line और 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.

Replace और reverse करना

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 और ख़ाली 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. 1Function header ठीक वैसा लिखें जैसा पूछा है, जैसे def COUNTLINES():।
  2. 2दिए नाम और mode 'r' से file खोलें; with बेहतर है या close() याद रखें।
  3. 3सही reading method चुनें: characters/words के लिए read(), lines के लिए readlines() या for-loop।
  4. 4Compare करने से पहले strip() से punctuation/newline हटाएँ।
  5. 5जैसा पूछा है वैसे final count print या return करें।
पूरे marks दिलाने वाले steps

अक्सर पूछे जाने वाले प्रश्न (FAQ)

Text file में words कैसे गिनें?
read() से file पढ़ें, split() से तोड़ें (जो किसी भी whitespace पर तोड़ता है) और मिली list का len() लें।
Words compare करते समय strip() क्यों?
File के words में अक्सर punctuation या newline होती है, जैसे "east." या "worm.\n"। strip(".,") या strip() उन्हें हटाता है ताकि comparison सही हो।
← Class 12 Computer Science
🔗

Share this topic with a friend

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

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

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

अगला topicpickle के साथ Binary Files आपकी प्रगति: 6 / 26 (23%) · Lesson 7 / 26 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें