Write a Python program to count all the line having a as first character || Count number of lines in Python - Creation Code
Why counting the number of lines is important?
Counting the number of characters is important because almost all the text boxes that rely on user input have a certain limit on the number of characters that can be inserted. For example, the character limit on a Facebook post is 63,206 characters. Whereas, for a tweet on Twitter the character limit is 140 characters and the character limit is 80 per post for Snapchat. We will make a change on this process we will just count the number of lines that have 'a' as the first character.
Approach:
- Open the file in reading mode and assign a file object named 'file'
- Assign 0 to the counter variable
- Read the content of the file using the read function and assign it to a variable named 'content'
- Create a list of the content where the elements is split wherever they encounter an '\n'
Implement:
Suppose here we create a file called creationcode.txt and we need to read this file
Code:
#opening the file in read mode
file = open("creationcode.txt",'r')
#creating a variable for counting the number of lines
counter = 0
#reading the file
content = file.read()
#split the line to convert every line into an array
list = content.split("\n")
for i in list:
if i[0] == 'a':
counter += 1
print("This is the number of lines having a as first character")
print(counter)
Output:
This is the number of lines having a as first character
3
Comments
Post a Comment