Python program to read a file line by line. This program will read a txt file line by line and count the number of line started with a given alphabet. This python project is useful for beginners and CBSE KV School Class 11 and Class 12 students computer science practical file and NIELIT O Level module.
Write a program to read a file story.txt and print the contents of file along with the number of lines starting with A.
Steps to make a python program to read a file line by line
Create a txt file say story.txt in Notepad.
story.txt should be in the same directory as the program idle program.
Python Code of Program
Explanation of code used in program
f=open(“story.txt”,”r”) #opening a story.txt in read mode
st=f.readlines() #string take f.readlines(), st reads all lines
c=0 #counter is at zero
print(“Contents of file :”)# It prints the content of file
for i in st: #for i from start of the st to last of st for loop goes on
print(i) #It prints i
if i==”A”: #if the line first letter is A
c+=1 #then counter increases by one
print(“\nFILE END“) #This print file end in new line
print()#This print a blank line
print(“Number of lines starting with ‘A’ =”,c) #prints the number of lines starting with A
This above text file story.txt file is taken as first input and the output is given in the below pic. It shows it has read the file and counted the n.o of lines starting with A as zero. Which is correct.
Output Python program to read a file line by line
Output – 1
2nd Output with new text
Now as Archit lives in city is added in the paragraph in the starting line. The counter should display 1. This is shown below in the output as 1 . This above text file story.txt file is taken as second input and the output is given in the below pic. It shows it has read the file and counted the n.o of lines starting with A as one. Which is correct
Output Python program to read a file line by line-
Download source code – click here
For more python programs – click here