Program to read a text file in python. Today, we are going to learn, a program to read a text file and further print the contents of file along with number of vowels present in it using python language. This python program for beginners is useful for computer classes. This project is for the CBSE Class 11 and 12 computer science practical file.
How our Python program will work ?
We have to first create a .txt Notepad pad file in the same directory location in which our program will be there. We will give a name to the text file, in our program give it a name as story.txt. The notepad file contains paragraph of which we have to calculate the number of vowels. We must be aware that in English Language, Vowels are five alphabets a,e,i,o,u.
Write a program to read a file story.txt and print the contents of file along with number of vowels present in it.
Write the following python code in shell window.
Understand the code used in program
f=open(“story.txt”,’r’) #f opens the file story.txt in readable format
st=f.read() #the contents are feeded in other variable
print(“Contents of file :”)#it is printed
print(st) #print the whole story.txt file
c=0 #Inital counter is zero
v=[‘a’,’e’,’i’,’o’,’u’] #these are 5 vowels
for i in st: #for every character present in story.txt this for loop will operate
if i.lower() in v: #charaters are made lower case and been checked wheter they are vowels
c=c+1 # If the characters are vowels counter increases
print(“*****FILE END*****”) #loop is endedat the end of the output will be FILE END.
print() #print a new line
print(“Number of vowels in the file =”,c)# at the end of the loop it will print number of vowels
f.close() # close the document file
Output for Read a file text file story.txt in python
Here the paragraph in story.txt is read first then printed with the number of vowels present.
Source code of program to read a text file in python – click here
For more python programs- click here