Write a function in Python to count and display the number of lines starting with alphabet

Write a function in Python to count and display the number of lines starting with alphabet “A” present in a text file “LINES.TXT”, e.g., the file “LINE.TXT” contains the following lines:

A boy is playing there.

There is a playground.

An aeroplane is in the sky.

Alphabets & numbers are allowed in password.

The function should display the output as 3.

 

Python function that reads a text file called “LINES.TXT” and counts the number of lines starting with the alphabet “A”:

def count_lines_starting_with_a(filename):
    try:
        with open(filename, 'r') as file:
            lines = file.readlines()
            count = 0

            for line in lines:
                if line.strip().startswith('A'):
                    count += 1

            return count

    except FileNotFoundError:
        print(f"File '{filename}' not found.")
        return None


filename = 'LINES.TXT'
result = count_lines_starting_with_a(filename)

if result is not None:
    print(f"Number of lines starting with 'A': {result}")

 

Make sure you have a text file named “LINES.TXT” in the same directory as the Python script, and the file should contain the lines you provided. The function reads the file using readlines() to get a list of all lines. It then iterates over each line, strips leading and trailing whitespace using strip(), and checks if the line starts with the letter ‘A’ using startswith('A'). If the condition is met, it increments the count variable. Finally, it prints the count of lines starting with ‘A’.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *