Write a Python program to count all the lines having a as first character

 Python program to count all the line having a as first character

In this article, we will be solving a problem of Data File Handing in which we have to work with text file. You will learn to create a python program to count all the line having a as first character. So, without wasting time let's with the code. If you like the article, share it on your coding communities and social media groups so that more people can take advantage of the content.



Logic and Explanation

For the above problem, we first have to open the text file in read mode in our python program. In my example, I am taking a text file name "content.txt" which is present in the same directory where this python file is present. So, I just written the name of file otherwise you have to write the complete path of the file to open the file. This is the code to open file in read mode.

with open("content.txt") as f:

Now, to count the number of lines starting with a we will create a count_a variable with initial value equal to 0. We will increase it's value by one as we will spot a line starting with a. Read further code for more clarity.

count_a = 0

Now, we will iterate through the file using for loop. As we will iterate through it, lines will come one by one in "line" variable. Then we will check whether the character at index 0 of the line is 'a' or not. If it is 'a' then we will add one to count_a variable.

for line in f:
    if line[0].lower() == "a":
        count_a += 1

Now, we are almost done with the code. At last we will print the value of count_a variable.

print("No of lines starting with a = ", count_a)

Here's the complete source code of the program to count all the line having a as first character.

with open("content.txt") as f:
    count_a = 0
    
    for line in f:
        if line[0].lower() == "a":
            count_a += 1

print("No of lines starting with a = ", count_a)


So, I hope you liked the article and you would have found the content of the article useful and helpful for you. Share this article in your coding communities so that more people can take advantage of the content. Also, In case of any doubt feel free to ask in the comments below.

Enjoy Coding!!!


Also Read :-





For any doubts feel free to ask in comments below.
Stay Connected to Us for more such Courses and Projects.

Post a Comment

For any doubts feel free to ask in comments below.
Stay Connected to Us for more such Courses and Projects.

Post a Comment (0)

Previous Post Next Post