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 thetotal number of lines starting with 'A', 'B', and 'C' from the fileMyFile.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
Program to count characters spaces lines in file content
Print the number of lines, words, and characters in a file.Write a program to print the number of lines, words, and characters in a file.Note: Take the input file name from the user.Sample Test CasesTest Case 1:Expected Output:Enter·file·name:·InputData1.txtLine·count·=·7Word·count·=·51Char·count·=·306
Which of the following command is used to count the total number of lines, words, and characters contained in a file?0.5 Markswcountwccatless
Find the count of letters and words in a file.
Count the sentences, words and characters in a fileWrite a Python program that reads a file and prints the number of lines, words, and characters in the file.Input Format:The input will be a single string, which is the name of the file to be read.Output Format:The output will be three separate lines, each containing a count:The first line will contain the number of lines in the file, prefixed with "Sentences: ".The second line will contain the number of words in the file, prefixed with "Words: ".The third line will contain the number of characters in the file, prefixed with "Chars: ".Sample Test CasesTest Case 1:Expected Output:file·name:input1.txtSentences:·8Words:·34Chars:·228Test Case 2:Expected Output:file·name:input2.txtSentences:·7Words:·51Chars:·306
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.