Count Lines From a Text File Starting with a Specific Word
Q. Write a program to count lines from a text file starting with specific word.
# Count only those lines starting with "I" def read_data(): count = 0 f = open("text.txt",'r') s = f.readlines() for i in s: if i == 'I': count += 1 else: pass print(count,""+"lines") read_data()
Explanation: Here we have defined a function read_data(). Inside read_data() function we have also created a file object “f” and opened our text file in read mode ie. “r” mode.
In next step, we have initialized all the values to variable “s“. And used readlines() function to get read our file line by line. The readlines() function return the output in list format.
Note: Here inside function, we have used count variable and initialize with value 0.
So, now we have the complete text data in list format and we can slice each line using list indexing method. We implemented for loop() to iterate over each element of list which is the each lines of our text files stored in list format.
if i == ‘I’:
Here inside for loop, if condition checks for the first letter of each line starting with the letter ‘I‘. If condition sets true then it increments the value of count by +1 else it skip that line.
Programming questions on Text Files
- WAP to define a method to read text document line by line.
- WAP to define a method in python to read lines from a text file starting with an alphabet F.
- WAP to define a method which display only those lines starting with an alphabet A or F.
- WAP to define a method to display only those lines which are bigger than 50 characters.
- WAP to define a method to count total number of characters in our text file.
- WAP to define a method to count total numbers of word available in our text file.
- WAP to define a method which counts the occurrence of particular word in a text file.
- WAP to define a method which only print the words having more than 5 characters.
- WAP to define a method which counts the occurrence of “is”, “to” in a text file.
Programming questions on Binary Files