Python Program to calculate number of lines in a text file














































Python Program to calculate number of lines in a text file



'''Description:
1. The program will ask the user to enter the file name.
2. Initially the counter is set to zero.
3. The program fetches each line from the file and simultaneously increments the counter.
4. It prints the final count.
5. It will also consider the blank lines of the text file. If you dont want to include the blank lines you need to use strip function.
6. Time module has been imported to calculate the execution time.
'''

'''Text File: check.txt
1.From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
2.Return-Path: <postmaster@collab.sakaiproject.org>
3.Received: from murder (mail.umich.edu [141.211.14.90])
4. by frankenstein.mail.umich.edu (Cyrus v2.3.8) with LMTPA;
5. Sat, 05 Jan 2008 09:14:16 -0500
6.X-Sieve: CMU Sieve 2.3
7.Received: from murder ([unix socket])
8. by mail.umich.edu (Cyrus v2.2.12) with LMTPA;
9. Sat, 05 Jan 2008 09:14:16 -0500
10.Received: from holes.mr.itd.umich.edu (holes.mr.itd.umich.edu [141.211.14.79])
11. by flawless.mail.umich.edu () with ESMTP id m05EEFR1013674;
12. Sat, 5 Jan 2008 09:14:15 -0500
13.Received: FROM paploo.uhi.ac.uk (app1.prod.collab.uhi.ac.uk [194.35.219.184])
14. BY holes.mr.itd.umich.edu ID 477F90B0.2DB2F.12494 ;
15. 5 Jan 2008 09:14:10 -0500
16.Received: from paploo.uhi.ac.uk (localhost [127.0.0.1])
17. by paploo.uhi.ac.uk (Postfix) with ESMTP id 5F919BC2F2;
18. Sat, 5 Jan 2008 14:10:05 +0000 (GMT)
19.Message-ID: <200801051412.m05ECIaH010327@nakamura.uits.iupui.edu>
'''


import time
start = time.time()
class File:
#create a constructor
def __init__(self, filename):
self.count = 0
fhandle = open(filename)
for line in fhandle:
self.count = self.count + 1
end = time.time()
filename = input("Enter file name: ")
file = File(filename)
print(f'Number of Lines: {file.count}')
print(f'Execution Time: {end - start}')


'''Input:
Enter file name: check.txt
'''

'''Output:
Number of Lines: 19
'''


Comments