Write a program to count a total number of lines and count thetotal number of lines starting with 'A', 'B', and 'C' from the fileMyFile.txt
Question
Write a program to count a total number of lines and count the total number of lines starting with 'A', 'B', and 'C' from the file MyFile.txt
Solution
Sure, here is a Python program that does that:
def count_lines(filename):
total_lines = 0
lines_starting_with_A = 0
lines_starting_with_B = 0
lines_starting_with_C = 0
with open(filename, 'r') as file:
for line in file:
total_lines += 1
if line.startswith('A'):
lines_starting_with_A += 1
elif line.startswith('B'):
lines_starting_with_B += 1
elif line.startswith('C'):
lines_starting_with_C += 1
return total_lines, lines_starting_with_A, lines_starting_with_B, lines_starting_with_C
total, A, B, C = count_lines('MyFile.txt')
print(f"Total lines: {total}")
print(f"Lines starting with A: {A}")
print(f"Lines starting with B: {B}")
print(f"Lines starting with C: {C}")
This program opens the file MyFile.txt
in read mode, then iterates over each line in the file. It increments the total line count for each line, and checks the first character of each line to see if it's 'A', 'B', or 'C', incrementing the respective count if it is. Finally, it prints out the total number of lines and the number of lines starting with 'A', 'B', and 'C'.
Similar Questions
Which of the following command is used to count the total number of lines, words, and characters contained in a file?0.5 Markswcwcountcatless
File Handling:●Write a program that reads a text file and prints the number of words in it
Write a python program to print the number of occurrences of a substring into a line
Write a python program to count the number of characters of alphabets 'O' and 'i' from the given file
Question 5 of 15Which command prints newline, word, and byte counts for each file?Option 1echoOption 2wcOption 3grep
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.