Class 12 Python File Handling - Questions &
Solutions
1. Count lines in a text file
with open('[Link]','r') as f:
print(len([Link]()))
2. Count words in a text file
with open('[Link]','r') as f:
data = [Link]()
print(len([Link]()))
3. Count vowels
with open('[Link]','r') as f:
text = [Link]().lower()
v = "aeiou"
print(sum(1 for ch in text if ch in v))
4. Count uppercase & lowercase
with open('[Link]','r') as f:
t = [Link]()
u = sum(1 for c in t if [Link]())
l = sum(1 for c in t if [Link]())
print(u, l)
5. Digits & special characters
with open('[Link]','r') as f:
t = [Link]()
d = sum([Link]() for c in t)
s = sum(not [Link]() and not [Link]() for c in t)
print(d, s)
6. Lines starting with vowel
with open('[Link]') as f:
for line in f:
if [Link]() and [Link]()[0].lower() in 'aeiou':
print([Link]())
7. Lines starting with consonant
with open('[Link]') as f:
for line in f:
if [Link]() and [Link]()[0].isalpha() and [Link]()[0].lower() not in 'aeiou':
print([Link]())
8. Words ending with vowel
with open('[Link]') as f:
for word in [Link]().split():
if word[-1].lower() in 'aeiou':
print(word)
9. Words ending with 'e'
with open('[Link]') as f:
print(sum(1 for w in [Link]().split() if [Link]('e')))
10. Lines containing 'Python'
with open('[Link]') as f:
for line in f:
if 'Python' in line:
print([Link]())
11. Words with double letters
with open('[Link]') as f:
words = [Link]().split()
for w in words:
for i in range(len(w)-1):
if w[i] == w[i+1]:
print(w)
break
12. Count lines starting with consonant
with open('[Link]') as f:
print(sum(1 for line in f if [Link]() and [Link]()[0].isalpha() and [Link]()[0].lower
13. Words > 5 characters
with open('[Link]') as f:
for w in [Link]().split():
if len(w) > 5:
print(w)
14. Words starting & ending with vowel
with open('[Link]') as f:
print([w for w in [Link]().split() if w[0].lower() in 'aeiou' and w[-1].lower() in 'aeiou'])
15. Reverse each line
with open('[Link]') as f:
for line in f:
print(line[::-1].strip())
16. Sort words alphabetically
with open('[Link]') as f:
words = sorted([Link]().split(), key=[Link])
print(words)
17. Count sentences
with open('[Link]') as f:
text = [Link]()
print([Link]('.') + [Link]('!') + [Link]('?'))
18. Words starting capital
with open('[Link]') as f:
print([w for w in [Link]().split() if w[0].isupper()])
19. Lines > 10 words
with open('[Link]') as f:
for line in f:
if len([Link]()) > 10:
print([Link]())
20. Repeated words
with open('[Link]') as f:
words = [Link]().split()
seen = set()
for w in words:
if [Link](w) > 1:
[Link](w)
print(seen)
21. Words with digit
with open('[Link]') as f:
print([w for w in [Link]().split() if any([Link]() for c in w)])
22. [Link] to [Link] (start vowel lines)
with open('[Link]') as f, open('[Link]','w') as t:
for line in f:
if [Link]() and [Link]()[0].lower() in 'aeiou':
[Link](line)