Python Programing Lab R16 EXERCISE - 7(b)
Aim:
Write a program to compute the number of characters, words and lines in a file.
Description:
lines=0
words=0
chars=0
f=open('netaji.txt','r')
for line in f:
wordslist=line.split()
lines+=1
words+=len(wordslist)
chars+=len(line)
print("no.of characters",chars)
print("no.of words",words)
print("no.of lines",lines)
Output:
Traverse each character in the file so that we can find number of characters, words and lines in a text file. Here, We are using the some of the basic methods of files.
We already discussed about open() and close() in the previous programs.
read():
If we need to extract string that contains all characters in the file, We can use read(). TheSyntax for read() in Python is:
str = file_object.read()
Program:
words=0
chars=0
f=open('netaji.txt','r')
for line in f:
wordslist=line.split()
lines+=1
words+=len(wordslist)
chars+=len(line)
print("no.of characters",chars)
print("no.of words",words)
print("no.of lines",lines)
Output:
No comments