Practical 1: - Write a Python function dispword() to read a text file named
STORY.TXT line by line and display each word separated by the symbol #.
Objective:
To develop the ability to read a text file line by line, split the content into words,
and display each word separated by the symbol # using Python.
Program: - def
dispword(filename):
"""
Reads a text file line by line and displays each word separated by '#'.
Parameters:
filename (str): The name or path of the text file to read.
""" try:
with open(filename, 'r') as file:
for line in file:
words = line.strip().split() # Split line into words
hashed = '#'.join(words) # Join words using '#'
print(hashed) except FileNotFoundError:
print(f"Error: File '{filename}' not found.")
except Exception as e:
print(f"An error occurred: {e}")
dispword('STORY.TXT') #calling function
Output:-
Practical 2: - Write a Python program to read a text file (e.g., STORY.TXT) and
display the total number of:
• Vowels
XII C. S. (083) Practical Record File Page 1
• Consonants
• Uppercase letters
• Lowercase letters
Objective: To understand file handling and character classification in Python by
reading a text file and counting vowels, consonants, uppercase, and lowercase
letters.
Program: - def
count_chars(filename):
"""
Reads a text file and counts the number of:
- Vowels - Consonants - Uppercase letters - Lowercase
letters Parameters:
filename (str): The name or path of the file to read.
Prints:
Count of vowels, consonants, uppercase and lowercase letters.
"""
vowels = 'AEIOUaeiou' vowel_count = consonant_count =
upper_count = lower_count = 0
try: with open(filename,
'r') as file: for line in file:
for char in line:
if char.isalpha(): # Check if it's a
letter if char in vowels:
vowel_count += 1
else:
consonant_count +=
1 if char.isupper():
upper_count += 1
elif char.islower():
lower_count += 1
# Display the results
print(f"Vowels: {vowel_count}")
print(f"Consonants: {consonant_count}")
print(f"Uppercase letters: {upper_count}")
print(f"Lowercase letters: {lower_count}")
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage
count_chars('STORY.TXT')
XII C. S. (083) Practical Record File Page 2
Output:-
XII C. S. (083) Practical Record File Page 3
Practical 3: Write a function in Python to count the number of lines in a text file
named
STORY.TXT which start with the alphabet 'A'.
Objective:
To understand how to read text files line by line and apply string functions to
count specific conditions like lines starting with a particular character.
Program: - def
countAln(filename):
"""
Counts the number of lines in the text file that start with the alphabet 'A'.
Parameters:
filename (str): The name or path of the file to read.
Prints:
Number of lines starting with the letter 'A'.
""" count
=0 try:
with open(filename, 'r') as file: for line in file:
if line.lstrip().startswith('A'): # Ignore leading spaces
print(line)
count += 1 print(f"Number of lines
starting with 'A': {count}")
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage countAln('STORY.TXT')
Output:-
Practical 4: Write a method/function DISPLAYWORDS() in Python to read lines
from a
text file STORY.TXT and display those words which are less than 4 characters.
XII C. S. (083) Practical Record File Page 4
Objective:
To practice file handling in Python by reading from a text file and
filtering/displaying words based on their length.
Program: - def
DISPLAYWORDS():
"""
Reads the text file STORY.TXT and displays words that are less than 4
characters long.
""" try: with open("STORY.TXT",
"r") as file: for line in file:
words =
line.strip().split() for
word in words: if
len(word) < 4:
print(word) except
FileNotFoundError:
print("Error: File 'STORY.TXT' not found.")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage
DISPLAYWORDS()
Output:-
XII C. S. (083) Practical Record File Page 5
Practical 5: Write a method COUNTLINES() in Python to read lines from a text
file
TESTFILE.TXT and display the number of lines which are not starting with any
vowel.
Objective:
To develop file-handling skills in Python by reading lines from a file and applying
string-based conditional checks to count specific types of lines.
Program: - def
COUNTLINES():
"""
Reads lines from TESTFILE.TXT and counts how many lines do NOT start with a
vowel.
""" vowels = ('A', 'E', 'I', 'O', 'U', 'a', 'e', 'i',
'o', 'u') count = 0 try: with
open("TESTFILE.TXT", "r") as file: for
line in file:
stripped_line = line.lstrip() # Remove leading
spaces if stripped_line and not stripped_line[0] in
vowels:
count += 1 print(f"The number of lines not
starting with any vowel - {count}") except FileNotFoundError:
print("Error: File 'TESTFILE.TXT' not found.")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage
COUNTLINES()
Output:-
XII C. S. (083) Practical Record File Page 6
Practical 6: Write a function ETCount() in Python that reads each character of a
text file
TESTFILE.TXT and counts the occurrence of the letters 'E' and 'T' (both uppercase
and lowercase). Display the count individually.
Objective:
To develop Python file-handling skills by reading a text file character-by-character
and counting specific letter occurrences, case-insensitively.
Program: - def
ETCount():
"""
Reads each character from TESTFILE.TXT and counts how many times
'E'/'e' and 'T'/'t' appear in the file.
""" e_count
=0 t_count =
0
try: with open("TESTFILE.TXT", "r")
as file: for line in file: for
char in line: if char == 'E' or
char == 'e':
e_count += 1
elif char == 'T' or char == 't':
t_count += 1
print(f"E or e: {e_count}")
print(f"T or t: {t_count}")
except FileNotFoundError:
print("Error: File 'TESTFILE.TXT' not found.")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage ETCount()
Output:-
Practical 7: Write a Python function that removes all the lines containing the
character 'a'
from a file (say SOURCE.TXT) and writes the remaining lines to another file (say
CLEANED.TXT).
XII C. S. (083) Practical Record File Page 7
Objective:
To use file-handling concepts in Python to read from one file, filter out lines
based on a condition, and write to another file.
Program: - def
removeLines():
"""
Reads lines from 'SOURCE.TXT' and writes lines that do not
contain the character 'a' to 'CLEANED.TXT'.
"""
try:
with open("SOURCE.TXT", "r") as infile, \
open("CLEANED.TXT", "w") as outfile:
for line in infile: if 'a' not in line:
outfile.write(line)
print("Lines without 'a' have been written to 'CLEANED.TXT'.")
except FileNotFoundError:
print("Error: 'SOURCE.TXT' not found.")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage
removeLines()
Output:-
XII C. S. (083) Practical Record File Page 8
-
Practical 8: Write a Python function govWeb() that reads a file URLs.txt and
displays all the words that contain gov.in.
Objective:
To read from a text file and extract/display only those words which contain a
specific domain — gov.in.
Program: - def
govWeb():
"""
Reads 'URLs.txt' and displays all words containing 'gov.in'
""" try: with
open("URLs.txt", "r") as file:
for line in file:
words =
line.strip().split() for
word in words: if
"gov.in" in word:
print(word)
except FileNotFoundError:
print("Error: File 'URLs.txt' not found.")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage govWeb()
Output:-
9|Page
Practical 9: Write a Python function that displays all the lines containing the
word 'vote' from a text file "Elections.txt".
Objective:
To write a Python function that reads a text file named "Elections.txt" and
displays all the lines that contain the word "vote". This helps in extracting
relevant information related to voting from the file efficiently.
Program: - def
showVoteLines():
"""
Reads 'Elections.txt' and displays all lines containing the word 'vote'.
"""
try:
with open("Elections.txt", "r") as file:
for line in file:
if 'vote' in line.lower(): # Case-insensitive
check print(line.strip())
except FileNotFoundError:
print("Error: File 'Elections.txt' not found.")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage
showVoteLines()
Output:-
10 | P a g e
Practical 10: - Write a Python function that displays all the words starting and
ending with a vowel from a text file "Report.txt". The consecutive words should
be separated by a space in the output.
Objective:
To write a Python function that reads a text file named "Report.txt" and displays
all the words that start and end with a vowel, with consecutive words separated
by spaces. This helps in filtering specific patterns in text data based on vowel
placement in words.
Program: - def
vowelWords():
"""
Reads 'Report.txt' and displays all words that start and end with a
vowel. The words are printed space-separated.
"""
vowels = "aeiouAEIOU"
result = []
try: with open("Report.txt",
"r") as file: for line in file:
words = line.strip().split()
for word in words:
# Remove punctuation like .,!? from the word
clean_word = word.strip(".,!?;:\"'()[]{}") if clean_word and
clean_word[0] in vowels and clean_word[-1] in vowels:
result.append(clean_word) print("
".join(result)) except
FileNotFoundError:
print("Error: File 'Report.txt' not found.")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage
vowelWords()
Output:-
11 | P a g e
12 | P a g e