Python Program to Count the Number of Lines in a File Using readline() Function
# Python Program to Count the Number of Lines in a File Using readline() Function
#open the file to read
with open(r"file.txt", 'r') as fp:
# readlines() function to read all the lines at a single go
lines = len(fp.readlines())
print('Total Number of lines:', lines)
Output:
Total Number of lines: 5
Python Program to Count the Number of Lines in a File Using enumerate
# Python Program to Count the Number of Lines in a File Using enumerate
# open the file to read
with open(r"file_one.txt", 'r') as fp:
# enumerate() function adds a counter to an iterable and returns it in a format of enumerating objects
for count, line in enumerate(fp):
pass
print('Total Number of lines:', count + 1)
Output:
Total Number of lines: 8
Python Program to Count the Number of Lines in a File Using counter
# Python Program to Count the Number of Lines in a File Using counter
# Opening a file
file = open("one.txt", "r")
Counter = 0
# Reading from file
Content = file.read()
CoList = Content.split("\n")
for i in CoList:
if i:
Counter += 1
print("This is the number of lines in the file")
print(Counter)
Output:
This is the number of lines in the file
4
Python Program to Count the Number of Lines in a File Using sum() Function
# Python Program to Count the Number of Lines in a File Using sum() Function
# Reading from file
with open(r"file1.txt", 'r') as fp:
lines = sum(1 for line in fp)
print('Total Number of lines:', lines)
Output:
Total Number of lines: 6
About The Author
Shailendra Bramhvanshi, Founder at Techaroha Solutions Private Limited and CEO at Newtum Solutions Private Limited. BlockChain Experts with 12 years of IT Experience in of all aspects of running Organization and Project Management. I have created different coins to help the business to bring more trust. Recently deployed a stable coin in India TrueINR and working on few cryptocurrency exchanges. My Team is being rated as a top 10 blockchain service provider in India by Silicon India