Important Python Programs - Text File Handling (Class 12 CBSE)
1. Create a text file and write content to it
f = open("example.txt", "w")
f.write("Hello World\nWelcome to Python\n")
f.close()
2. Read and display the content of a text file
f = open("example.txt", "r")
print(f.read())
f.close()
3. Read a file line by line and print
f = open("example.txt", "r")
for line in f:
print(line.strip())
f.close()
4. Count total number of lines in a text file
f = open("example.txt", "r")
count = len(f.readlines())
print("Total lines:", count)
f.close()
5. Count the number of words in a file
f = open("example.txt", "r")
words = f.read().split()
print("Total words:", len(words))
f.close()
6. Count the number of uppercase/lowercase characters
f = open("example.txt", "r")
content = f.read()
upper = sum(1 for c in content if c.isupper())
lower = sum(1 for c in content if c.islower())
print("Uppercase:", upper, "Lowercase:", lower)
f.close()
7. Display only those lines which start with a vowel
vowels = 'AEIOUaeiou'
with open("example.txt", "r") as f:
for line in f:
if line[0] in vowels:
print(line.strip())
8. Display only those lines which contain the word 'Python'
with open("example.txt", "r") as f:
for line in f:
if "Python" in line:
print(line.strip())
9. Append new content to a file
f = open("example.txt", "a")
f.write("This is an appended line.\n")
f.close()
10. Write only even length words from a file to a new file
with open("example.txt", "r") as fin, open("even_words.txt", "w") as fout:
for line in fin:
words = line.split()
even_words = [word for word in words if len(word) % 2 == 0]
fout.write(" ".join(even_words) + "\n")
11. Count and print number of lines that start with 'T' or 't'
count = 0
with open("example.txt", "r") as f:
for line in f:
if line.lower().startswith('t'):
count += 1
print("Lines starting with T/t:", count)
12. Find and print longest word in the text file
with open("example.txt", "r") as f:
words = f.read().split()
longest = max(words, key=len)
print("Longest word:", longest)